Search code examples
phpzend-frameworkyii2

Is there a yii2 equivalent to zend1 fetchAssoc?


I am trying to upgrade a zend1 site to yii2, and the table models frequently use fetchAssoc to get records from the database with the ID column as the array key. Is there a yii2 equivalent?

Example: PHP

$query = table::find()                
    ->select(['id',
         'firstName',
         'lastName'
    ])->indexBy('id'); //no effect?

$command = $query->createCommand();

$results = $command->queryAll();

Datebase contains

[
    [
       id=>15
       firstName=>"fname",
       lastName=>"lname"
    ],
    [
       id=>16
       firstName=>"fname2",
       lastName=>"lname2"
    ]
]

I want it to return as

[
    15=>
       [
          id=>15
          firstName=>"fname",
          lastName=>"lname"
       ],
    16=>
       [
          id=>16
          firstName=>"fname2",
          lastName=>"lname2"
       ]
]

instead of

[
    0=>
       [
          id=>15
          firstName=>"fname",
          lastName=>"lname"
       ],
    1=>
       [
          id=>16
          firstName=>"fname2",
          lastName=>"lname2"
       ]
]

If I add

$results=array_combine(array_column($results,key($results[0])), $results);

That creates the index, but I would prefer to use the framework to do it.

Thanks


Solution

  • To do it, it needs asArray(true) and indexBy('column name or function') and then call all, or column, or one.

    $results = table::find()->asArray(true)->indexBy('id')->all()
    

    I was previously using

    $command = $query->createCommand();
    $results = $command->queryAll();
    

    Final code example:

    $query = table::find()                
        ->select(['id',
             'firstName',
             'lastName'
        ])->indexBy('id')->asArray(true);
    $results=$query->all();