如何在CakePHP 3.x中对查询生成器结果使用哈希?
这是我的密码如何在CakePHP 3.x中对查询生成器结果使用哈希?,cakephp,cakephp-3.0,Cakephp,Cakephp 3.0,这是我的密码 $all = $this->find() ->select(['ProductCircles.id', 'ProductCircles.type', 'ProductCircles.name']) ->order(['ProductCircles.type']) ->all() ->toArray(); Log::write('error', $all);
$all = $this->find()
->select(['ProductCircles.id', 'ProductCircles.type', 'ProductCircles.name'])
->order(['ProductCircles.type'])
->all()
->toArray();
Log::write('error', $all);
$all = Hash::combine($all, '{n}.ProductCircles.id', '{n}.ProductCircles.name', '{n}.ProductCircles.type');
$all
是ProductCircle实体的数组
但是,哈希组合无法像我预期的那样对数据进行操作
请告知
$all
应为ProductCircle实体的数组:
2015-03-15 08:04:36 Error: Array
(
[0] => App\Model\Entity\ProductCircle Object
(
[_accessible:protected] => Array
(
[name] => 1
[type] => 1
[product_count] => 1
[products_in_circles] => 1
)
[_properties:protected] => Array
(
[id] => 27
[type] => MATERIAL
[name] => Wood
)
[_original:protected] => Array
(
)
[_hidden:protected] => Array
(
)
[_virtual:protected] => Array
(
)
[_className:protected] => App\Model\Entity\ProductCircle
[_dirty:protected] => Array
(
)
[_new:protected] =>
[_errors:protected] => Array
(
)
[_registryAlias:protected] => ProductCircles
)
这正是我所期望的
我想使用Hash::combine来获得如下数组:
$result:
[
[MATERIAL] => [
[27] => [
Wood
]
]
不使用哈希,但使用内置于查询对象中的收集方法:
$combined = $this->find()
->select(['ProductCircles.id', 'ProductCircles.type', 'ProductCircles.name'])
->order(['ProductCircles.type'])
->combine('id', 'name', 'type')
->toArray();
要扩展José的答案(并使用
extract()
,因为这正是我需要的答案):
更多信息:哈希组合无法按我的预期对数据进行操作。-你需要具体点。展示一个$al(来自发现)l的样本,以及你期望最终结果的样子。你的答案是正确的。我必须知道:a)烹饪书中说明的这种组合方法在哪里?b) 为什么我不需要向查询中添加
->all()
?c) 如果您注意到cake3食谱中的Hash文章,\Utility\Hash::extract,它实际上建议直接在查询对象上使用Hash。对吗?就在这里,阅读所有的例子,这样你就能理解它为什么有效,以及可以使用的所有其他方法:在这种情况下,我认为关于Hash的cake3书籍例子需要一些修改。这个周末晚些时候我会对它做一些修改。是不是我不能用ORM做这个Hash::combine($q,{n}.id',{n}',{n}.group_id')
<代码>(新集合($row->layout_box))->combine('id',function($entity){return$entity;},'col')->toArray()
$query = $this->MyTable->find('all', [
'contain' => [
'ProductCircles',
],
// ...
]);
return $query->all()->extract('ProductCircles.name');