Using Yii, how can I get an array from an Active Record.
Say something like this:
array(\'foo\', \'bar\', \'lala\')
From something like thi
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.
Use the Yii2 ArrayHelper by including to your controller this will convert a model data to an associated 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]));
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
Don't use ActiveRecord. Use CDBCommand->queryColumn()