Query for retrieving data records for a specific date range in Laravel 4

前端 未结 2 1507
北海茫月
北海茫月 2021-02-11 04:54

I have a table having record_date and corresponding amount field.I was trying to retrieve total amount grouping by the months of the date .

I a

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-11 05:22

    I would avoid using Eloquent for a more complex query such as this. Just stick with the query builder:

    $data = DB::table('table_name')
      ->select(DB::raw('MONTH(record_date)'),DB::raw('YEAR(record_date)'),DB::raw('SUM(amount)'))
      ->where('record_date', '>', DB::raw('DATE_SUB(now(), INTERVAL 6 MONTH)'))
      ->groupBy(DB::raw('YEAR(record_date)'))
      ->groupBy(DB::raw('MONTH(record_date)'))
      ->get();
    

    Unfortunately, since you are using so many MySQL functions, you need to add in a lot of DB::raw methods. But it should work. This is untested but it should be very close.

提交回复
热议问题