Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel:有效求和嵌套关系(已加载)_Php_Laravel_Laravel 5_Laravel 5.6 - Fatal编程技术网

Php Laravel:有效求和嵌套关系(已加载)

Php Laravel:有效求和嵌套关系(已加载),php,laravel,laravel-5,laravel-5.6,Php,Laravel,Laravel 5,Laravel 5.6,在Laravel 5.6中,我有许多嵌套的关系。我正在寻找一种有效的方法来对关系的每个最外层节点上的属性求和 例如,每一个都由一个hasMany链接 国家->州->城市->街道->房屋 如果我想把某个国家的所有房子->卧室相加,最有效的方法是什么 目前,我的记忆中有一个国家,如下所示: $country->load('states.cities.streets.houses'); 我试着: $country->states->cities->streets->ho

在Laravel 5.6中,我有许多嵌套的
关系。我正在寻找一种有效的方法来对关系的每个最外层节点上的属性求和

例如,每一个都由一个
hasMany
链接

国家
->
->
城市
->
街道
->
房屋

如果我想把某个国家的所有
房子->卧室
相加,最有效的方法是什么

目前,我的记忆中有一个国家,如下所示:

$country->load('states.cities.streets.houses');
我试着:

$country->states->cities->streets->houses->pluck('bedrooms')->sum()
但是得到:

此集合实例上不存在属性[cities]

我可以通过
foreach
在各种关系上循环来实现这一点,但感觉必须在Laravel中内置一种更高效的代码方式。我错过了什么


谢谢

您可以尝试以下代码

Country::with(['states.cities.streets.houses' => function ($query) {
    $query->select('bedrooms', '...');
}])->sum('bedrooms');

我目前正在使用
State
City
上的
hasManyThrough
解决此问题,然后:

$country->load('cities.houses');
echo $country->cities->sum(function ($city) {
                    return $city->houses->sum('bedrooms');
                });

但感觉还是不太好。非常感谢任何更好的答案。

如果您的结果很大,您不应该在应用层中得到它们的总和。尝试使用SQL求和函数

如果您想以雄辩的方式进行,这应该是您的最佳解决方案:

Country::with(['states.cities.streets.houses' => function ($query) {
    $query->select('bedrooms');
}])->sum('bedrooms');
如果不使用这样的DB查询:

DB::table('countries')
    ->join('states', '..', '..')
    ->join('cities', '..', '..')
    ->join('streets', '..', '..')
    ->join('houses', '..', '..')
    ->selectRaw('SUM(bedrooms) as sum')
    ->pluck('sum')[0]

我创建了一个具有无限级别的
HasManyThrough
关系:

安装后,您可以这样使用它:

DB::table('countries')
    ->join('states', '..', '..')
    ->join('cities', '..', '..')
    ->join('streets', '..', '..')
    ->join('houses', '..', '..')
    ->selectRaw('SUM(bedrooms) as sum')
    ->pluck('sum')[0]
类国家扩展模型{
使用\Staudenmeir\elokenthasmanydeep\hassrelationships;
公共职能机构(){
返回$this->hasManyDeep(House::class、[State::class、City::class、Street::class]);
}
}
$sum=$country->houses()->sum(‘卧室’);

您是否尝试过使用count()
:?稍微短一点:
$country->cities->pull('houses')->collapse()->sum('beddrooms')
我如何调整这一点以使用我已经存储在内存中的
country
?使用
$country->states()->加入('cities',',',',','''''''','''''''''')->加入('streets',','''''''''''''''''''''''''''->selectRaw('SUM(卧室)as SUM')->pull('SUM')[0]
两年后,我正在使用你的图书馆,这很好。谢谢