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

itstrueimryan's avatar

Basic Query - Order By Count

Not sure what I'm doing wrong, but this isn't producing the right results. The query I want to replicate is simple - no relationships or anything. Just trying to get the tag_ids from tag_topic with the highest number of occurrences:

SELECT tag_id FROM `tag_topic` GROUP BY tag_id ORDER BY COUNT(tag_id) DESC LIMIT 8

And here is my Eloquent code:

$tagIds = \DB::table('tag_topic')
            ->groupBy('tag_id')
            ->orderBy(\DB::raw('count(tag_id)', 'DESC'))
            ->take(8)
            ->lists('tag_id');

And I just get some really wacky results, clearly not the right ones.

0 likes
1 reply
doanh's avatar
doanh
Best Answer
Level 1

@itstrueimryan In orderBy, you have 1 mistake

->orderBy(\DB::raw('count(tag_id)', 'DESC'))
// should be
->orderBy(\DB::raw('count(tag_id)'), 'DESC')

Try again and post your result

2 likes

Please or to participate in this conversation.