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

前端 未结 9 2595
北荒
北荒 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条回答
  • 2021-02-15 13:19

    For yii2 , use:

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

    or

    yii\helpers\ArrayHelper::getColumn(MyModel::find()->all(), 'name'));
    
    0 讨论(0)
  • 2021-02-15 13:22

    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:24

    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:24

    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:24

    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:27

    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',
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题