Yii 模型要数组吗?

发布于 2024-10-07 14:51:04 字数 62 浏览 0 评论 0原文

如何将 Trips::model()->findAll() 的结果转换为数组?

How can I convert the result of Trips::model()->findAll() to an array?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

み零 2024-10-14 14:51:04

我在这里假设您只需要检索裸数组,而不是任何关联的模型对象。

这样就可以了:

$model = Trips::model();
$trips = $model->getCommandBuilder()
               ->createFindCommand($model->tableSchema, $model->dbCriteria)
               ->queryAll();

这就像 Yii::app()->db->createCommand('SELECT * FROM tbl')->queryAll(); 示例,除了:

  • < p>它会向模型询问表名;您不需要在模型和查询中都写入表名称。

  • 您可以在 $model 上调用 作用域 函数 首先,例如
    $model = Trips::model()->short()->destination('德克萨斯州奥斯汀');
    这样做意味着您可以使用模型现有的查询快捷方式,而不是直接将它们放入查询中。

相比之下, $trips = Trips::model()->findAll(); (使用 foreach)有点浪费,因为您从数据库中提取行,设置一堆东​​西,然后把它们全部扔掉。它对于小型结果集来说效果很好,但如果您正在查看一长串旅行列表,我不会使用它。

警告:
不过,如果这只是一个快速原型,请务必使用 createCommand() 或 findAll() 和循环示例。

I'm going on the assumption here that you only need to retrieve just the bare arrays, and not any associated model objects.

This will do it:

$model = Trips::model();
$trips = $model->getCommandBuilder()
               ->createFindCommand($model->tableSchema, $model->dbCriteria)
               ->queryAll();

This is like the Yii::app()->db->createCommand('SELECT * FROM tbl')->queryAll(); examples, except:

  • It'll ask the model for the table name; you won't need to write the table name in both the model and the query.

  • You can call scoping functions on $model first, eg.
    $model = Trips::model()->short()->destination('Austin, TX');
    Doing this means you can use the model's existing query shortcuts, instead of putting them in the query directly.

In contrast, the $trips = Trips::model()->findAll(); (using foreach) is a bit wasteful, in that you're pulling the rows from the database, setting up a bunch of objects, and then throwing them all away. It'll work fine for small result sets, but I wouldn't use that if you're looking at a long list of Trips.

Caveat:
If this is just a quick prototype, though, by all means use the createCommand() or findAll()-and-loop examples.

记忆之渊 2024-10-14 14:51:04

这是正确的方法,它遵循 Yii 约定。

$trips = Trips::model()->findAll();
$arr = array();
foreach($trips as $t)
{
    $arr[$t->id] = $t->attributes;
}

当您有复杂的查询,并且您发现使用 Yii 约定很难创建这些查询时,可以使用此方法。

Yii::app()->db->createCommand('SELECT * FROM tbl')->queryAll();

例如,当您需要将模型中的所有数据传递到数组时。您不能直接传递它,因为它确实传递了一些您不需要的 ActiveRecord 数据信息。

This is the right way to do, it follows Yii conventions

$trips = Trips::model()->findAll();
$arr = array();
foreach($trips as $t)
{
    $arr[$t->id] = $t->attributes;
}

This is used when you have complex queries, those you find difficult to create with Yii conventions.

Yii::app()->db->createCommand('SELECT * FROM tbl')->queryAll();

For example, when you need to pass all the data from the model to an array. You cannot pass it directly as it does pass some ActiveRecord data information that you don't need.

猫性小仙女 2024-10-14 14:51:04

这是一样的。

$array = CHtml::listData(Trips::model()->findAll(), 'trip_id', 'trip_name');

This is same.

$array = CHtml::listData(Trips::model()->findAll(), 'trip_id', 'trip_name');
伤痕我心 2024-10-14 14:51:04

简单简单的方法:我使用 listData() 方法来制作数组到下拉菜单,我认为这会对您有所帮助..检查这个示例:

代码:

<?php 
     /*you can use here any find method you think 
     proper to return your data from db*/
     $models = Trips::model()->findAll();

     // format models resulting using listData     
     $tripsArray = CHtml::listData($models, 'id', 'name');    

     print_r($tripsArray);
?>

输出:

array(
 '1'=>'trip1',
 '2'=>'trip2',
 '3'=>'trip3',
)

Easy and simple way: I use listData() method to make array to dropdown menus, and I think this will help you.. check this example:

code:

<?php 
     /*you can use here any find method you think 
     proper to return your data from db*/
     $models = Trips::model()->findAll();

     // format models resulting using listData     
     $tripsArray = CHtml::listData($models, 'id', 'name');    

     print_r($tripsArray);
?>

output:

array(
 '1'=>'trip1',
 '2'=>'trip2',
 '3'=>'trip3',
)
喜爱皱眉﹌ 2024-10-14 14:51:04
$model = Trips::model()->findAll(); 
$arr = CHtml::listData($model, 'trip_id', 'trip_name');
var_dump($arr);

CHtml::listData() 将返回一个数组值。

$model = Trips::model()->findAll(); 
$arr = CHtml::listData($model, 'trip_id', 'trip_name');
var_dump($arr);

CHtml::listData() will return an array value.

窝囊感情。 2024-10-14 14:51:04

您可以创建收藏CMap继续与她合作

$collections = new CMap();
foreach (YourModel::model()->findAll(['index' => 'id']) as $key => $row) {
   $collections->add($key,$row->attributes);
}
var_dump($collections ->toArray());

You can create collections CMap continue to work with her

$collections = new CMap();
foreach (YourModel::model()->findAll(['index' => 'id']) as $key => $row) {
   $collections->add($key,$row->attributes);
}
var_dump($collections ->toArray());
淡莣 2024-10-14 14:51:04

我很确定您可以这样做:

$trips = Trips::model()->findAll();
$arr = array();
foreach($trips as $t)
{
    $arr[$t->id] = $t->attributes;
}

我假设您将属性“id”作为模型的主键。

I'm pretty sure you can do this:

$trips = Trips::model()->findAll();
$arr = array();
foreach($trips as $t)
{
    $arr[$t->id] = $t->attributes;
}

I'm assuming you have the attribute 'id' as your model's primary key.

毁虫ゝ 2024-10-14 14:51:04

我使用 $array = CJSON::decode(CJSON::encode($model)); 将 $model 转换为 $array。

i use $array = CJSON::decode(CJSON::encode($model)); to convert $model to $array.

花桑 2024-10-14 14:51:04

你可以用这个。

$Trips::model()->findAll(array('index'=>'trip_id'));
if(count($Trips)>0)
            {                   
                $TripsArrayList=array();
                foreach($Tripsas as $singleTrip)
                {                   
                    $TripsArrayList[]=array('trip_id'=>$singleTrip->trip_id,'name'=>$singleTrip->name);         
                }                   
            }

你的输出将是

Array
    (
      [0] => Array
                 (
                   [trip_id] => 1
                   [name] => Nashik
                 )
      [1] => Array
                 (
                   [trip_id] => 2
                   [name] => Puna
                 ) 
      [2] => Array
                 (
                   [trip_id] => 3
                   [name] => Mumbai
                 ) 
    )

You can use this.

$Trips::model()->findAll(array('index'=>'trip_id'));
if(count($Trips)>0)
            {                   
                $TripsArrayList=array();
                foreach($Tripsas as $singleTrip)
                {                   
                    $TripsArrayList[]=array('trip_id'=>$singleTrip->trip_id,'name'=>$singleTrip->name);         
                }                   
            }

Your output will be

Array
    (
      [0] => Array
                 (
                   [trip_id] => 1
                   [name] => Nashik
                 )
      [1] => Array
                 (
                   [trip_id] => 2
                   [name] => Puna
                 ) 
      [2] => Array
                 (
                   [trip_id] => 3
                   [name] => Mumbai
                 ) 
    )
天涯离梦残月幽梦 2024-10-14 14:51:04
$cats = Category::model()->findAll();
$count_cats = count($cats);
if($count_cats > 0){
    $arr_category = array();
    foreach($cats as $cat)
        array_push($arr_category,$cat->attributes);
}
print_r($arr_category);

->结果

Array(
[0] => Array
    (
        [cat_id] => 2
        [title] => Đương đại
        [title_full] => Đương đại
        [desc] => 
        [alias] => duong-dai
        [p_id] => 0
        [type] => 1
        [status] => 1
        [sort_order] => 2
        [selected] => 0
    )
[1] => Array
    (
        [cat_id] => 164
        [title] => Nhiệt đới
        [title_full] => Nhiệt đới
        [desc] => 
        [alias] => nhiet-doi
        [p_id] => 0
        [type] => 1
        [status] => 1
        [sort_order] => 0
        [selected] => 0
    )
[...])
$cats = Category::model()->findAll();
$count_cats = count($cats);
if($count_cats > 0){
    $arr_category = array();
    foreach($cats as $cat)
        array_push($arr_category,$cat->attributes);
}
print_r($arr_category);

-> result

Array(
[0] => Array
    (
        [cat_id] => 2
        [title] => Đương đại
        [title_full] => Đương đại
        [desc] => 
        [alias] => duong-dai
        [p_id] => 0
        [type] => 1
        [status] => 1
        [sort_order] => 2
        [selected] => 0
    )
[1] => Array
    (
        [cat_id] => 164
        [title] => Nhiệt đới
        [title_full] => Nhiệt đới
        [desc] => 
        [alias] => nhiet-doi
        [p_id] => 0
        [type] => 1
        [status] => 1
        [sort_order] => 0
        [selected] => 0
    )
[...])
命硬 2024-10-14 14:51:04

假设您的问题需要所有属性,一个更紧凑的解决方案可以为您提供按 id 散列的所有属性,您可以使用 CActiveRecord 的“属性”伪属性,如下所示:

CHtml::listData(Trips::model()->findAll(), 'id', 'attributes')

Assuming from your question that you want all the attributes, a more compact solution to give you all attributes hashed by id, you can use CActiveRecord's 'attributes' pseudoproperty as follows:

CHtml::listData(Trips::model()->findAll(), 'id', 'attributes')
哆兒滾 2024-10-14 14:51:04

在 yii2 中你可以使用 asArray()

$someArray = Sometable::find()->select(['id', 'name', 'role'])->asArray()->all();

In yii2 you can use asArray()

$someArray = Sometable::find()->select(['id', 'name', 'role'])->asArray()->all();
草莓酥 2024-10-14 14:51:04

对数组使用 DAO

$array = Yii::app()->db->createCommand('SELECT * FROM tbl')->queryAll();

Use DAO for arrays

$array = Yii::app()->db->createCommand('SELECT * FROM tbl')->queryAll();
追风人 2024-10-14 14:51:04

不要为此使用 CHtml::listData。它必须用于其他目的。
CDbCriteria 有一个index 属性适合您的要求。

//1st option
Trips::model()->findAll(array('index'=>'trip_id'));

//2nd option
$c = new CDbCriteria();
$c->index = 'trip_id';
Trips::model()->findAll($c);

Don't used CHtml::listData for this. It has to be used for other purposes.
There is an index property of CDbCriteria which is suitable for you requirement.

//1st option
Trips::model()->findAll(array('index'=>'trip_id'));

//2nd option
$c = new CDbCriteria();
$c->index = 'trip_id';
Trips::model()->findAll($c);
む无字情书 2024-10-14 14:51:04

简单使用:

$trips = Trips::model()->findAll();

$trips_array = CJSON::decode(CJSON::encode($trips));

注意:这不是好方法,但会返回数组

Use simply:

$trips = Trips::model()->findAll();

$trips_array = CJSON::decode(CJSON::encode($trips));

Note: This is not good way but returns array

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文