Yii - How to get an array of values ​​from Active Record

Using Yii, how can I get an array from Active Record.

Say something like this:

array('foo', 'bar', 'lala')

From something like this:

 MyTable::model()->findall() 
+8
arrays activerecord yii
source share
9 answers

Do not use ActiveRecord . Use CDBCommand->queryColumn()

0
source share

If I understand you correctly:

 $users = User::model()->findAll(); $usersArr = CHtml::listData( $users, 'id' , 'name'); print_r( $usersArr ); 

It will give you an id => name array

 Array { 2 => 'someone', 20 => 'kitty', 102 => 'Marian', // ... } 
+24
source share

The ActiveRecord class has an attribute called attributes. You can find his description here: http://www.yiiframework.com/doc/api/1.1/CActiveRecord#attributes-detail .

To get all the attributes in an array, use this: $var = $model->attributes;

+6
source share

For yii2 use:

 yii\helpers\ArrayHelper::map(MyModel::find()->all(), 'id', 'name')); 

or

 yii\helpers\ArrayHelper::getColumn(MyModel::find()->all(), 'name')); 
+5
source share

You can also do something like

 $countries = Country::model()->findAll(); array_values(CHtml::listData($countries, 'country_id', 'country_name')); 

which returns an array of all country names, or

 array_keys(CHtml::listData($countries, 'country_id', 'country_name')); 

which returns an array of all country identifiers.

+3
source share

What about:

 Yii::app()->db->createCommand() ->setFetchMode(PDO::FETCH_COLUMN,0) ->select("mycolumn") ->from(MyModel::model()->tableSchema->name) ->queryAll(); 

Result:

 array('foo', 'bar', 'lala') 
+1
source share

Use Yii2 ArrayHelper, including it in your controller, this will convert the model data into a linked array

  use yii\helpers\ArrayHelper; $post = ArrayHelper::toArray(ClientProfilesForm::findOne(['id' => 1])); //or use it directly by $post = yii\helpers\ArrayHelper::toArray(ClientProfilesForm::findOne(['id' => 1])); 
+1
source share

Use Chtml For This - Ugly Hack! Applying this solution is the best way to find this:

 public function queryAll($condition = '', $params = array()) { $criteria = $this->getCommandBuilder()->createCriteria($condition, $params); $this->applyScopes($criteria); $command = $this->getCommandBuilder()->createFindCommand($this->getTableSchema(), $criteria); $results = $command->queryAll(); return $results; } 

You can add this code to the ActiveRecord class, for example:

 class ActiveRecord extends CActiveRecord { //... } 

And, use this method:

 return $model->queryAll($criteria); 

You can learn more about this link .

0
source share

if you are using Yii1.1 and you need to get ALL the data from AR as the array you need to take care of this. Yii1.1 AR does not have this function out of the box

Yii2 AR has asArray () method, it is very useful

I hope my answer helps someone

0
source share

All Articles