Answer the question
In order to leave comments, you need to log in
How to display the number of records in the query result when grouping groupBy?
The task is to select the number of records for a certain year from the table, grouped by months.
I don’t understand where to specify count () so that not records would be displayed, but only their number was counted.
$items = MyModel::whereYear('created_at', '2021')
->get()
->groupBy(function($events) {
return Carbon::parse($events->created_at)->format('m');
});
{
"11":[
{
"id":4,
"type":1,
"manager_id":6,
"order_id":2341,
"created_at":"2021-11-14T21:02:55.000000Z",
"updated_at":null
}
],
"12":[
{
"id":2,
"type":1,
"manager_id":1,
"order_id":2345,
"created_at":"2021-12-14T21:02:55.000000Z",
"updated_at":null
},
{
"id":3,
"type":1,
"manager_id":3,
"order_id":2344,
"created_at":"2021-12-10T21:02:55.000000Z",
"updated_at":null
}
]
}
Answer the question
In order to leave comments, you need to log in
$items = DB::table('table')
->whereYear('created_at', 2021)
->selectRaw('month(created_at) month, count(*) count')
->groupBy('month')
->get();
Apparently you don't really understand what you're doing. You need to immediately do a groupBy, and then pull out the data from the table by calling get (). Read the documentation, there is also about count and you will understand how Eloquent works
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question