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
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.
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();