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

ilex01's avatar

How do order by sum (query builder/sql)

How do I oder by sum with this query:

$votes = DB::table('votes')
	->where('website_id', $site->id)
	->sum('stars');
0 likes
2 replies
s4muel's avatar
s4muel
Best Answer
Level 50

that query only returns one number. but if you want to select all pages ordered by sum of their ratings and their ratings, you could do something like this:

DB::table('posts')
    ->selectRaw("website_id, SUM(stars) AS website_rating_sum")
    ->groupBy('website_id')
    ->orderByDesc('website_rating_sum')
    ->get();

you get this:

[
    [
        `website_id` => 5,
        `website_rating_sum` => 10,
    ],
    [
        `website_id` => 1,
        `website_rating_sum` => 3,
    ],
...
Sinnbeck's avatar

I assume you mean you want to order websites. Lets say you are using eloquent and have a votes() relationship set up

Website::query()
    ->withSum('votes', 'stars')
    ->orderByDesc('votes_sum_stars')
    ->get();
1 like

Please or to participate in this conversation.