关系中雄辩的分组

时间:2017-05-29 05:23:34

标签: laravel eloquent

有三种型号:

品牌(身份证,姓名)

示例可能是

1Mc Donald's

2Help Desk

商城(id,name)

示例:

1Central Mall

奥特莱斯(id,name,brand_id,mall_id)

示例可能是

1Mc Donald's Ground Floor11

2Mc Donald's Food Court11

3Help Desk Ground Floor21

4Help Desk First Floor21

5Help Desk Second Floor21

已经在模型中定义了关系,我想得到Mall的结果:

App\Mall::with('outlets.brand')->where('id',1)->get();

给我一​​个结果:

App\Mall {
id: 1,
name: "Central Mall",
outlets:{
'1' => {  
  name:"Mc Donald's",
  outlets: {
            1 => {
                  'id' => 1,
                  'name'=> "Mc Donald's Ground Floor",
                 } ,
            2 => {
                  'id' => 2,
                  'name'=> "Mc Donald's Food Court",
                 } , 
           ....
           }
       }
   }
}

1 个答案:

答案 0 :(得分:0)

这是未经测试的,但使用[Collection::groupBy](https://laravel.com/docs/5.4/collections#method-groupby)功能,您应该可以对这些插座进行分组。

$mall = App\Mall::with('outlets.brand')->find(1);
$outlets = $mall->outlets->groupBy('brand.name');