Skip to content
Advertisement

SQL request with GROUP BY and SUM in Eloquent

I just want make a simple sql request in my laravel application.

I’m not very comfortable with Eloquent aha.

This is the SQL request I want to make with eloquent :

select user_id, project_id, sum(hours)
FROM time_entries
WHERE spent_on BETWEEN '2018-04-10' AND '2018-12-10'
GROUP BY user_id, project_id

I’ve been trying something like :

TimeEntries::whereBetween('spent_on', [($request->input('debut')), ($request->input('fin'))])->groupBy('user_id')->sum('hours');

(but you can see it’s hopeless)

Advertisement

Answer

Use selectRaw().

TimeEntries::whereBetween('spent_on', [($request->input('debut')), ($request->input('fin'))])->groupBy(['user_id', 'project_id'])->selectRaw('user_id , project_id, sum(hours) as sum')->get();
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement