E
E
Eugene2021-12-15 01:05:38
MySQL
Eugene, 2021-12-15 01:05:38

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');
    });

Now it comes out like this
{
   "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

2 answer(s)
J
jazzus, 2021-12-15
@atachrus

$items = DB::table('table')
    ->whereYear('created_at', 2021)
    ->selectRaw('month(created_at) month, count(*) count')
    ->groupBy('month')
    ->get();

V
Vyacheslav Plisko, 2021-12-17
@AmdY

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 question

Ask a Question

731 491 924 answers to any question