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

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

我有三个模型 CountryProvinceDistrictCountryProvinceDistrict 模型都有一对多的关系。而ProvinceDistrict模型是一对多的关系。 District 模型有 province_id 作为外键。

District 模型中,我有一个总体要求和。我想得到每个省的人口总和。

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

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;

上面的 returns 省份 ID 但我想要省份名称。

试试这个:

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

您告诉它按 province_id:$population->groupBy('province_id') 分组。相反,您可以将一个函数传递给 groupBy() 集合方法,告诉它如何对内部的项目进行分组:

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

尝试这样的事情:

$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');
});