有没有等同于 zend1 fetchAssoc 的 yii2?
Is there a yii2 equivalent to zend1 fetchAssoc?
我正在尝试将一个 zend1 站点升级到 yii2,并且 table 模型经常使用 fetchAssoc 从数据库中以 ID 列作为数组键获取记录。是否有 yii2 等价物?
示例:
PHP
$query = table::find()
->select(['id',
'firstName',
'lastName'
])->indexBy('id'); //no effect?
$command = $query->createCommand();
$results = $command->queryAll();
数据库包含
[
[
id=>15
firstName=>"fname",
lastName=>"lname"
],
[
id=>16
firstName=>"fname2",
lastName=>"lname2"
]
]
我希望它 return 为
[
15=>
[
id=>15
firstName=>"fname",
lastName=>"lname"
],
16=>
[
id=>16
firstName=>"fname2",
lastName=>"lname2"
]
]
而不是
[
0=>
[
id=>15
firstName=>"fname",
lastName=>"lname"
],
1=>
[
id=>16
firstName=>"fname2",
lastName=>"lname2"
]
]
如果我加上
$results=array_combine(array_column($results,key($results[0])), $results);
创建索引,但我更愿意使用框架来完成它。
谢谢
为此,它需要 asArray(true) 和 indexBy('column name or function') 然后调用 all,或 column,或 one。
$results = table::find()->asArray(true)->indexBy('id')->all()
我之前使用
$command = $query->createCommand();
$results = $command->queryAll();
最终代码示例:
$query = table::find()
->select(['id',
'firstName',
'lastName'
])->indexBy('id')->asArray(true);
$results=$query->all();
我正在尝试将一个 zend1 站点升级到 yii2,并且 table 模型经常使用 fetchAssoc 从数据库中以 ID 列作为数组键获取记录。是否有 yii2 等价物?
示例: PHP
$query = table::find()
->select(['id',
'firstName',
'lastName'
])->indexBy('id'); //no effect?
$command = $query->createCommand();
$results = $command->queryAll();
数据库包含
[
[
id=>15
firstName=>"fname",
lastName=>"lname"
],
[
id=>16
firstName=>"fname2",
lastName=>"lname2"
]
]
我希望它 return 为
[
15=>
[
id=>15
firstName=>"fname",
lastName=>"lname"
],
16=>
[
id=>16
firstName=>"fname2",
lastName=>"lname2"
]
]
而不是
[
0=>
[
id=>15
firstName=>"fname",
lastName=>"lname"
],
1=>
[
id=>16
firstName=>"fname2",
lastName=>"lname2"
]
]
如果我加上
$results=array_combine(array_column($results,key($results[0])), $results);
创建索引,但我更愿意使用框架来完成它。
谢谢
为此,它需要 asArray(true) 和 indexBy('column name or function') 然后调用 all,或 column,或 one。
$results = table::find()->asArray(true)->indexBy('id')->all()
我之前使用
$command = $query->createCommand();
$results = $command->queryAll();
最终代码示例:
$query = table::find()
->select(['id',
'firstName',
'lastName'
])->indexBy('id')->asArray(true);
$results=$query->all();