问题
I have an issues table, it has a column created_at, and status which can be 'Open' or 'Closed'
I need to get the count of issues depending on the status per month. I want to get something like this:
January 2018: {
open: 300,
closed: 28,
},
February 2018: {
open: 250,
closed: 80
}
I don't know if there's a better approach, I'm open to suggestion in how I would retrieve the data. Basically I'm creating an admin dashboard and want to display the data in a chart.
回答1:
Assuming you are using MySQL:
$months = Issue::select(
DB::raw("date_format(created_at, '%M %Y') month"),
DB::raw("sum(if(status = 'Open', 1, 0)) open"),
DB::raw("sum(if(status = 'Closed', 1, 0)) closed")
)->groupBy('month')->get();
You can set the key with keyBy()
:
$months = $months->keyBy('month');
来源:https://stackoverflow.com/questions/51027510/how-to-group-and-count-record-by-date-using-laravel