我确实有这个laravel集合
Collection {#239 ▼
#items: array:2 [▼
0 => array:21 [▼
"dueDate" => "2017-09-29"
"groupByCode" => "REMINDER"
"date" => "2017-09-29"
"number" => "9030014"
"status" => "Reminder"
"currencyCode" => "kr"
"amount" => 1745.0
"remainingAmount" => 1745.0
],
2 => array:21 [▼
"dueDate" => "2017-09-29"
"groupByCode" => "REMINDER"
"date" => "2017-09-29"
"number" => "9030014"
"status" => "Reminder"
"currencyCode" => "kr"
"amount" => 1345.0
"remainingAmount" => 1745.0
],
3 => array:21 [▼
"dueDate" => "2017-09-29"
"groupByCode" => "INVOICE"
"date" => "2017-09-29"
"number" => "9030026"
"status" => "invoice"
"currencyCode" => "kr"
"amount" => 2389.0
"remainingAmount" => 2389.0
]
]
}
现在我的问题是如何根据状态获取唯一的项目,上面的示例我有两个状态为Reminder的项目,而我希望保持相同的集合格式,但作为回报,只有一个项目的状态为“Reminder”with所有现有的密钥和总和将是两个提醒的总和....
我曾尝试使用`where('status',''Reminder') - > first()但不起作用,因为它只需要firts元素。
所以输出应该是这样的:
Collection {#239 ▼
#items: array:2 [▼
0 => array:21 [▼
"dueDate" => "2017-09-29"
"groupByCode" => "REMINDER"
"date" => "2017-09-29"
"number" => "9030014"
"status" => "Reminder"
"currencyCode" => "kr"
"amount" => TOTAL OF BOTH REMINDERS
"remainingAmount" => 1745.0
],
2 => array:21 [▼
"dueDate" => "2017-09-29"
"groupByCode" => "INVOICE"
"date" => "2017-09-29"
"number" => "9030014"
"status" => "Invoice"
"currencyCode" => "kr"
"amount" => 2312
"remainingAmount" => 1745.0
],
}
谢谢!
以下是代码:
$invoices = $this->boatService->getInvoices(cleanSsn(session('ssn')));
$invoices = collect($invoices)->whereIn('status', ['Reminder', 'Invoice']);
答案 0 :(得分:1)
您可以进行原始查询以对项目求和并按状态对其进行分组。试试这个:
$collection = \DB::table('invoices')
->select(\DB::raw('sum(amount) as amount_total, status'))
->groupBy('status')
->get();