flatMap it instead of plucking.
// omitted
->get()
->flatMap->cases
->sum()
Hi, I am looking to get the sum of values from a number of collections. If I do
foreach ($productions as $production) {
$productionCases = ProductionCase::where('production_id', $production->id)
->where('month', '>', $request->month)
->get()
->pluck('cases');
}
it returns
0: (17) [15, 20, 10, 0, 12, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1: (17) [4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
I was trying to use array_reduce but realized I am getting collections back. How do I reduce it so I get a single array with
(17) [19, 25, 16, 0, 12, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
@chrisgrim you should be able to achieve all of this in a query:
Production::selectRaw('DATE_FORMAT(month, "%Y-%m") as month, SUM(cases) as sum_cases')
->join('production_cases', 'productions.id', 'production_cases.production_id')
->where('month', '>', $request->month)
->groupByRaw('DATE_FORMAT(month, "%Y-%m")')
->get()
Please or to participate in this conversation.