Yii - How to get a values array from an Active Rec

2019-03-27 02:25发布

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

Say something like this:

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

From something like this:

MyTable::model()->findall()

9条回答
三岁会撩人
2楼-- · 2019-03-27 02:39

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

In order to get all attributes in an array, use this: $var = $model->attributes;

查看更多
看我几分像从前
3楼-- · 2019-03-27 02:40

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.

查看更多
不美不萌又怎样
4楼-- · 2019-03-27 02:41

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]));
查看更多
唯我独甜
5楼-- · 2019-03-27 02:46

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',
    // ...
}
查看更多
Viruses.
6楼-- · 2019-03-27 02:53

Don't use ActiveRecord. Use CDBCommand->queryColumn()

查看更多
唯我独甜
7楼-- · 2019-03-27 02:56

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.

查看更多
登录 后发表回答