链接组通过收藏?

时间:2018-03-06 20:41:23

标签: php cakephp cakephp-3.0

我有一个有3个关联的实体,其中2个是父/子,我想要groupBy并将它们嵌套在所有3个。

鉴于此实体:

(int) 0 => object(Furniture\Model\Entity\FurnitureItem) {

        'id' => (int) 155,
        'furniture_type_id' => (int) 32,
        'country' => object(Countries\Model\Entity\Country) {
             'id' => (int) 14
        },
        'furniture_types' => object(Furniture\Model\Entity\FurnitureTypes) {
            'id' => (int) 32,
            'furniture_master_types' => 
                object(Furniture\Model\Entity\FurnitureMasterTypes) {

                    'id' => (int) 142
             },
        },
}

其中FurnitureItem属于FurnitureTypesFurnitureTypes属于FurnitureMasterTypes以及FurnitureItem属于Countries,我想格式化我的结果,以便它是这样嵌套的:

FurnitureMasterTypes - >家具类型 - >国家 - > FurnitureItem

我已尝试$query->groupBy('furniture_types.furniture_master_types.id')执行第一级嵌套,但这显然会更改结果集,->groupBy('{item}.furniture_types.id')似乎不适用第二级分组。

book中没有嵌套组的例子,所以想知道如何解决这个问题?

我想要的结果示例:

[
    '142' => [ // FurnitureMasterType
        '32' => [ // FurnitureType
           '14' => [ // Country
              object(Furniture\Model\Entity\FurnitureItem) {
                  'id' => (int) 155
              }
            ]
        ]
    ]
]

理想情况下,如果我可以重组以包含很棒的实体级别信息,例如:

[
    object(Furniture\Model\Entity\FurnitureMasterTypes) {
        'id' => 142,
        'items' => [
            object(Furniture\Model\Entity\FurnitureTypes) {
               'id' => 32,
               'items' => [
                   object(Countries\Model\Entity\Country) {
                      'id' => 14,
                      'items' => [
                          object(Furniture\Model\Entity\FurnitureItem) {
                              'id' => (int) 155
                          }
                       ]
                    }
                ]
            }
        ]
    }
]

1 个答案:

答案 0 :(得分:1)

可能真的找到了一种方法来做到这一点,虽然我仍然完全确认结构是完整的/正确但似乎它正在发挥作用。

"John Smith".split(' ').rotate.join(' ') #=> "Smith John"

关键是$query->formatResults(function($results) { return $results->groupBy('furniture_types.furniture_master_types.id') ->map(function($row) { return collection($row)->groupBy('furniture_types.id') ->map(function($row) { return collection($row)->groupBy('country.id')->toArray(); })->toArray(); }); })->toArray(); 内部调用 - 我找到了here