Laravel Eloquent, group by month/year

后端 未结 6 2158
一整个雨季
一整个雨季 2020-12-10 05:04

i\'m trying to group my data by month and year.

$data ->select(DB::raw(\'count(id) as `data`\'),DB::raw(\'YEAR(created_at) year, MONTH(created_at) month\')         


        
6条回答
  •  悲&欢浪女
    2020-12-10 05:18

    Note: This is solution based on eloquent, and yes, it not the best approach, but as the question is, this is using eloquent. If you want faster way, you can do it with raw query.

    If you want to group your results for example by year, you can use closure where you will parse your datetime to desired format (year or month).

    Here is example of the code:

    $res= ModelName::where('someColumn','test')
          ->get()
          ->groupBy(function($val) {
          return Carbon::parse($val->created_at)->format('Y');
    });
    

提交回复
热议问题