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');
});