简体   繁体   English

如何在两个相关模型中使用PHP Laravel Eloquent groupBy和sum方法?

[英]How to use PHP Laravel Eloquent groupBy and sum method with two related models?

I have three models Country , Province and District . 我有CountryProvinceDistrict三个模型。 Country has a one-to-many relationship with both Province and District models. CountryProvinceDistrict模型都具有一对多关系。 And Province has a one-to-many relationship with District model. ProvinceDistrict模型之间存在一对多关系。 The District model has province_id as a foreign key. District模型具有province_id作为外键。

In the District model I have a population to sum. District模型中,我有一个总和。 I want to get the sum of a population for each province. 我想获得每个省的人口总数。

$population = Country::where(['name' => $c_name])->first()->districts;
$num = $population->groupBy('province_id')->map(function ($row) {
    return $row->sum('population_m');
});

SQL Query: SQL查询:

SELECT provinces.name, SUM(districts.population_m) AS population_m, SUM(districts.population_f) AS population_f FROM provinces
LEFT JOIN districts ON provinces.id = districts.province_id
GROUP BY provinces.name;

The above returns the province id but I want the province name with it. 上面的代码返回了省份ID,但我想要它的省份名称。

You are telling it to group by province_id: $population->groupBy('province_id') . 您正在告诉它按province_id分组: $population->groupBy('province_id') Instead, you can pass a function to the groupBy() collection method to tell it how to group the items inside: 相反,您可以将一个函数传递给groupBy()集合方法,以告诉它如何对内部项目进行分组:

https://laravel.com/docs/5.7/collections#method-groupby https://laravel.com/docs/5.7/collections#method-groupby

Try something like this: 尝试这样的事情:

$population = Country::where(['name' => $c_name])->first()->districts;
$num = $population->groupBy(function($district, $key) {
    return $district->province->name;
})->map(function ($row) {
    return $row->sum('population_m');
});

尝试这个:

$population = Country::where(['name' => $c_name])->first()->districts()->with('province')->get(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM