如何在CakePHP 3.x中对查询生成器结果使用哈希?

2nc8po8w  于 2022-11-12  发布在  PHP
关注(0)|答案(2)|浏览(148)

这是我的密码

$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::合并来做的是得到一个数组的数组,如下所示:

$result:
    [
        [MATERIAL] => [
                [27] => [
                        Wood
                ]
        ]
6psbrbz9

6psbrbz91#

不使用Hash,而是使用内置到查询对象中的集合方法:

$combined = $this->find()
    ->select(['ProductCircles.id', 'ProductCircles.type', 'ProductCircles.name'])
    ->order(['ProductCircles.type'])
    ->combine('id', 'name', 'type')
    ->toArray();
6tr1vspr

6tr1vspr2#

为了扩展José的答案(使用extract(),因为这是我需要的):

$query = $this->MyTable->find('all', [
    'contain' => [
        'ProductCircles',
    ],
    // ...
]);
return $query->all()->extract('ProductCircles.name');

更多信息:book.cakephp.org/3/en/core-libraries/collections.html#Cake\集合\集合::提取

相关问题