我有一个名为Spring Boot 2.1.6
的集合,如下所示:
@SpringBootApplication
@EnableBinding(Processor.class)
public class MyApplication {
private final Log log = LogFactory.getLog(MyApplication.class);
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@StreamListener(Processor.INPUT)
@SendTo(Processor.OUTPUT)
public String check(String payload) {
log.info(payload);
return payload;
}
}
现在我想获取detailed
项和Collection {#1421 ▼
#items: array:2 [▼
3943 => Collection {#1419 ▼
#items: array:2 [▼
0 => RoomPricingHistory {#923 ▶}
1 => RoomPricingHistory {#1042 ▶}
]
}
3944 => Collection {#1420 ▼
#items: array:2 [▼
0 => RoomPricingHistory {#1153 ▶}
1 => RoomPricingHistory {#1264 ▶}
]
}
]
}
ofc的RoomPricingHistory的总和,它可以是2项的总和,所以我想获取每个集合的总和,我如何实现该目标?
答案 0 :(得分:1)
Collection sum
方法可以进行回调,因此您可以定义要计算的内容。在这种情况下,您可以在主集合和回调中调用sum
,这将使您可以访问内部集合,也可以调用sum
。
$detailed->sum(function ($group) {
return $group->sum('sales_price');
});
Laravel 6.x Docs - Collections - Available Methods - sum
由于这不是您要查找的内容,因此可以使用类似mapWithKeys
的方法遍历集合,并为各组调用sum
以获取每个组的总和:
$sums = $detailed->mapWithKeys(function ($group, $key) {
return [$key => $group->sum('sales_price')];
});
Laravel 6.x Docs - Collections - Available Methods - mapWithKeys