我希望有人能帮助我解决我的问题。我正在处理 Laravel 5 的这个小关系问题。
问题:
我想获得“钱包”模型中“金额”列的总和。
我当前运行的代码。
public function children()
{
return $this->hasMany('App\Tree', 'parent_id','id')
->with('children')
->with('user')
->with('user.wallets');
}
注意:这会返回以下数据。
[{
...,
children: [...]
user: {
...,
wallets: [...] // return list of array
}
}]
我的解决方案没有成功。
return $this->hasMany('App\Tree', 'parent_id','id')
->with('children')
->with('user')
->with('user.wallets', function($q) {
$q->sum('amount');
});
想要的结果
[{
...,
children: [...]
user: {
...,
wallets: [
...,
amount: XXX.XX // e.g The total sum of the column, could be any number based on the sum of the column.
]
}
}]
最佳答案
您可以使用修改后的 withCount()
。更改您的 user
和 children
关系:
public function user()
{
return $this->belongsTo('App\User')
->withCount(['wallets as wallets_amount' => function($query) {
$query->select(DB::raw('sum(amount)'));
}]);
}
public function children()
{
return $this->hasMany('App\Tree', 'parent_id', 'id')
->with('children', 'user');
}
然后您可以使用$user->wallets_amount
访问总和:
关于php - 如何获取关系数据库中列的总和 "Laravel5",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49004334/