How to group and count record by date using Laravel?

北慕城南 提交于 2021-01-29 10:41:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!