Yii model to array?

2019-01-17 06:27发布

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

标签: arrays model yii
14条回答
闹够了就滚
2楼-- · 2019-01-17 07:02

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.

查看更多
Evening l夕情丶
3楼-- · 2019-01-17 07:03

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.

查看更多
登录 后发表回答