Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TheJacol2017's avatar

ELOQUENT join two tables and order by sum of column

Hello, I've got two tables - one with posts, second - with points. I want to get sum of points for one post and nextly order posts by this sum. How can i do it?

0 likes
4 replies
bobbybouwmann's avatar
Level 88

What have you tried so far? You can find lots of examples in the documentation for this

Joins: https://laravel.com/docs/5.5/queries#joins

Post::select('*', DB::raw('SUM(points) as total_points'))
    ->join('points', 'posts.id', '=', 'points.post_id')
    ->orderBy('total_points')
    ->get();
1 like
bobbybouwmann's avatar

Or even

Post::join('points', 'posts.id', '=', 'points.post_id')
    ->orderByRaw('SUM(points.point)')
    ->get();
1 like
TheJacol2017's avatar

Thanks, but it doesn't work...

I get error with this information:

Syntax error or access violation: 1055 'database1.rates.id' isn't in GROUP BY

and the same with all columns

Please or to participate in this conversation.