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

前端 未结 9 2583
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-15 13:12

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

Say something like this:

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

From something like thi

相关标签:
9条回答
  • 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')
    
    0 讨论(0)
  • 2021-02-15 13:19

    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.

    0 讨论(0)
  • 2021-02-15 13:20

    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.

    0 讨论(0)
  • 2021-02-15 13:27

    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]));
    
    0 讨论(0)
  • 2021-02-15 13:30

    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

    0 讨论(0)
  • 2021-02-15 13:32

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

    0 讨论(0)
提交回复
热议问题