我需要一些如何解决这个问题的指导,请指出我正确的方向。
我有四个模型设置:
1. Area (has many subareas)
2. Subarea (has many buildings and has many persons through buildings)
3. Building (has many persons)
4. Person (contains a field named age)
通过分区模型,我能够检索该分区内每栋建筑的平均年龄,因为分区与人之间存在“很多通过”关系:
$mySubareaModel::with(‘avg_age_per_building’)->get()
Subarea:
Name: xxx
Lat: yyy
Long: zzz
Building_avg_age: (a list of buildings and the avg age)
Building 1:
AvgAge: 30
Building 2:
AvgAge: 25
Building 3:
AvgAge: 21
到目前为止一直很好,但现在我想在与人没有直接关系的区域层面做同样的事情。 对于每个区域,我想要一个子区域列表及其平均年龄,如下所示:
Area:
Name: xxx
Subareas: (a list of subareas and the avg age)
Subarea 1:
AvgAge: 23
Subarea 2:
AvgAge: 21
我有什么选择?
我可以以某种方式利用在子区域级别生成列表的已经工作的代码吗?
$ myAreaModel :: with('subarea.avg_age_per_building') - > some_kind_of_joins_and aggregation_here
如果是这样,加入和聚合将如何?
答案 0 :(得分:1)
看看你们的关系,嵌套相关模型是不行的?
Have a look at nested eager loading
Area::with('subarea.building.person')->get();
更新
也许在这样的集合上执行操作可能就是你要找的东西。我还没有机会测试它,但它可能会指导你
$result = Area::with('subarea.building.person')->get();
return $result->subarea->map(function($subareas, $key){
return $subareas->building->map(function($buildings, $key){
return $buildings->reduce(function($carry, $building){
return $carry + $building->avg('age');
})/ count($buildings) *100;
});
});