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

前端 未结 2 1506
北海茫月
北海茫月 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.

    0 讨论(0)
  • 2021-02-11 05:27

    You need a raw query and you may try this (Not tested but should work):

    $data = DB::table('table_name')
      ->select(DB::raw('MONTH(record_date) as m, YEAR(record_date) as y, SUM(amount) as t'))
      ->whereRaw('record_date > DATE_SUB(now(), INTERVAL 6 MONTH)')
      ->groupBy(DB::raw('YEAR(record_date), MONTH(created_at)'))
      ->get();
    
    0 讨论(0)
提交回复
热议问题