yajra / laravel-datatables

jQuery DataTables API for Laravel
https://yajrabox.com/docs/laravel-datatables
MIT License
4.74k stars 862 forks source link

GroupBy not working. #3162

Open shankhadevpadam opened 1 month ago

shankhadevpadam commented 1 month ago

Group by not working with a data table.

$userPackages = UserPackage::query()
    ->with(['package:id,name'])
    ->selectRaw('departure_id, start_date, sum(total_amount) as total')
    ->groupByRaw('departure_id, start_date')
    ->get();

dump($userPackages);

The above snippet works fine in the Laravel controller method.

$userPackages = UserPackage::query()
    ->with(['package:id,name'])
    ->selectRaw('departure_id, start_date, sum(total_amount) as total')
    ->groupBy(['departure_id', 'start_date']);

return DataTables::eloquent($userPackages)

But this one is not working. It only works when an array of data table queries adds the ID field to the group. Like this

$userPackages = UserPackage::query()
    ->with(['package:id,name'])
    ->selectRaw('departure_id, start_date, sum(total_amount) as total')
    ->groupBy(['departure_id', 'start_date', 'id']);

return DataTables::eloquent($userPackages)

But it gives a different result

1st query returns 242
Datatable query returns 360 result. 
yajra commented 4 weeks ago

It is working fine for me.

Maybe you have an issue with your SQL. Since you are using eager loading, you need to include the foreign keys in your select statement. I guess you are missing the package_id?