Yii model to array?

87,833

Solution 1

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.

Solution 2

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.

Solution 3

This is same.

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

Solution 4

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',
)

Solution 5

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

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

Share:
87,833
Joeeee
Author by

Joeeee

Updated on January 02, 2020

Comments

  • Joeeee
    Joeeee over 4 years

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