Laravel对具有多个项目的集合求和 [英] Laravel Sum a Collection with multiple items
本文介绍了Laravel对具有多个项目的集合求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个与子表return $this->hasMany('App\Online', 'entry_id');
当尝试获取一个条目时,我可以像下面的示例一样汇总我的收藏集.
When trying to fetch one single Entry i'm able to sum my collection like in the example below.
$item = SettlementEntries::find($id);
$item->Online->sum('field'); // returns the correct sum
当$id
是一个数组时,我的问题开始了,所以我的结果包含2个SettlementEntries.
My problem starts when the $id
is an array, so my result contains 2 SettlementEntries.
$items = SettlementEntries::find($ids);
$items->Online->sum('field'); <- returns zero
检索这些款项的正确方法是什么?
What is the correct way to retrieve those sums?
推荐答案
Laravel的Collection
通过使用点符号使此操作非常容易. 此处.
Laravel's Collection
makes this very easy, by using dot notation. Some examples here.
简单方法(点符号):
$sum = $items->sum('Online.field');
更明确的(回叫):
或者,如果您想更加明确,例如使用条件/过滤器:提供一个Closure
:
Or, if you want to be more explicit, e.g. using conditions/filters: provide a Closure
:
$sum = $items->sum(function($item) {
return $item->Online->sum('field');
});
这篇关于Laravel对具有多个项目的集合求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文