在Yii1.x中,要想查询语句返回以特定列为键(key)的数组数据,代码如下(下述例子以表主键为返回数组索引):
$users = User::model()->findAll(array('condition'=>'status = 1', 'index'=> 'id'));
其中通过findAll方法传入的index参数将被CActiveRecord::populateRecords方法用来按该index为键来整理查询返回数据。
在Yii2中,由于查询构造实际实现者为ActiveQuery,因此相应的处理也移植到ActiveQuery类的indexBy方法中,代码如下:
User::find()->where('status=:status', [':status' => User::STATUS_ACTIVATED])->indexBy('id')->all();