Using Yii, how can I get an array from an Active Record.
Say something like this:
array(\'foo\', \'bar\', \'lala\')
From something like thi
For yii2 , use:
yii\helpers\ArrayHelper::map(MyModel::find()->all(), 'id', 'name'));
or
yii\helpers\ArrayHelper::getColumn(MyModel::find()->all(), 'name'));
How about:
Yii::app()->db->createCommand()
->setFetchMode(PDO::FETCH_COLUMN,0)
->select("mycolumn")
->from(MyModel::model()->tableSchema->name)
->queryAll();
The result would be:
array('foo', 'bar', 'lala')
You could 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 ids.
Use Chtml to this is a Ugly Hack! Apply this solution is the better way to this that I found:
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 an ActiveRecord class, e.g.:
class ActiveRecord extends CActiveRecord {
//...
}
And, use this way:
return $model->queryAll($criteria);
You can read more about in this link.
if you are using Yii1.1 and you need to get ALL data from AR as array you need to care about that it self. Yii1.1 AR doesn't have this feature out of the box
In Yii2 AR has asArray() method, it's very helpful
I hope my answer helps someone
If i understand you correctly:
$users = User::model()->findAll();
$usersArr = CHtml::listData( $users, 'id' , 'name');
print_r( $usersArr );
It will give you array id => name
Array {
2 => 'someone',
20 => 'kitty',
102 => 'Marian',
// ...
}