Laravel 集合集合中的项目总和字段
我想看看这是否可行,但我想得到集合集合中某个项中某个字段的总和 我的控制器中有以下各项:Laravel 集合集合中的项目总和字段,laravel,laravel-5,Laravel,Laravel 5,我想看看这是否可行,但我想得到集合集合中某个项中某个字段的总和 我的控制器中有以下各项: $prefiltered_contacts = Contact::with(['donations' => function ($query) use ($request) { $query->whereMonth('date_received', $request->month) ->whereYear('date_r
$prefiltered_contacts = Contact::with(['donations' => function ($query) use ($request) {
$query->whereMonth('date_received', $request->month)
->whereYear('date_received', $request->year);
}])->get();
$contacts = $prefiltered_contacts ->filter(function ($contact) {
return $contact->donations->isNotEmpty();
});
我的捐赠课程有以下内容:
public function monetary_donations(){
return $this->hasMany('App\Payments_Distribution', 'donation_id','id');
}
最后一部分是在Payments\u Distribution
类中,有一个名为amount
的字段
如果我直接来自捐赠模型,我将访问货币捐赠总额,如$捐赠->货币捐赠->金额('amount')代码>我会收到总数。但是,我如何从接触模型着手呢?或者,考虑到它需要通过一系列捐款才能获得金钱捐款,这是否可能?我正在尝试获取所有联系人捐款(和金钱捐款)的报告,并输出特定时期的金钱捐款小计 接受闭包作为参数。所以你可以这样做:
$sum = $donations->sum(function ($donation) {
return $donation->monetary_donations->sum('amount');
});
或更高一级(从$contacts
):
编辑:
我还建议使用SQL而不是collections来加载您的关系并过滤掉没有捐赠的联系人:
$contacts = Contact::with(['donations' => function ($query) use ($request) {
$query
->with('monetary_donations')
->whereMonth('date_received', $request->month)
->whereYear('date_received', $request->year);
}])
->whereHas('donations') // Filter out those without donations with SQL
->get();
$contacts = Contact::with(['donations' => function ($query) use ($request) {
$query
->with('monetary_donations')
->whereMonth('date_received', $request->month)
->whereYear('date_received', $request->year);
}])
->whereHas('donations') // Filter out those without donations with SQL
->get();