Laravel 8 根据条件 hasMany 求和数据
Laravel 8 sum data on condition hasMany
我总是出错:
Property [payment] does not exist on this collection instance.
但我已经在 User
上设置了 eloquent :
public function payment() { return $this->hasMany(Payment::class); }
当我使用 where
和 whereBetween
时它不起作用。
如果我这样做听起来不错:
User::first()->payment->sum('amount')
修补程序示例:
$l = User::whereBetween('created_at', ['2022-02-20', '2022-02-28'])->with('payment')->get()
$l->payment->sum('amount')
我只需要 1 行不在数组中的结果。因为我找到 table 页脚的总计。
您可以通过以下方式为关系添加条件
$users = User::whereBetween('created_at', [
'2022-02-20', '2022-02-28'
])->with(['payments'])
->get();
当您获取多个用户时,您需要遍历循环。那就是您的代码中缺少的内容
$users = $users->map(function ($user) {
$user['total_payment'] = $user->payments->sum('amount');
return $user;
});
然后
$grandTotal = $users->sum('total_payment');
试试这个
$l = User::whereBetween('created_at', ['2022-02-20', '2022-02-28'])->with('payment')->get();
$grandTotal = $l->map(function ($item) {
$item->total_amount = $item->payment->sum('amount');
return $item;
})->sum('total_amount');
我总是出错:
Property [payment] does not exist on this collection instance.
但我已经在 User
上设置了 eloquent :
public function payment() { return $this->hasMany(Payment::class); }
当我使用 where
和 whereBetween
时它不起作用。
如果我这样做听起来不错:
User::first()->payment->sum('amount')
修补程序示例:
$l = User::whereBetween('created_at', ['2022-02-20', '2022-02-28'])->with('payment')->get()
$l->payment->sum('amount')
我只需要 1 行不在数组中的结果。因为我找到 table 页脚的总计。
您可以通过以下方式为关系添加条件
$users = User::whereBetween('created_at', [
'2022-02-20', '2022-02-28'
])->with(['payments'])
->get();
当您获取多个用户时,您需要遍历循环。那就是您的代码中缺少的内容
$users = $users->map(function ($user) {
$user['total_payment'] = $user->payments->sum('amount');
return $user;
});
然后
$grandTotal = $users->sum('total_payment');
试试这个
$l = User::whereBetween('created_at', ['2022-02-20', '2022-02-28'])->with('payment')->get();
$grandTotal = $l->map(function ($item) {
$item->total_amount = $item->payment->sum('amount');
return $item;
})->sum('total_amount');