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

hillcow's avatar

MySQL to Laravel Database Query

Hey there, I need some help in transforming the following MySQL query to a Laravel Database query. I get this error: "Base table or view not found: 1146 Table 'forum.(tag_thread) tt' doesn't exist"

Raw MySQL:

select ta.name from tags ta join tag_thread tt on tt.tag_id = ta.id join (select * from threads order by id desc limit 100) th on tt.thread_id = th.id group by ta.name order by count(ta.name) desc limit 5

My Laravel Database Query:

DB::table('tags') ->select('ta.name') ->join('tag_thread tt', 'tt.tag_id', '=', 'ta.id') ->join(DB::raw('(select * from threads order by id desc limit 100) th'), 'tt.thread_id', '=', 'th.id') ->groupBy('ta.name') ->orderBy(DB::raw('count(ta.name)'), 'DESC') ->limit(5) ->get();

Any help is much appreciated, thank you!

0 likes
5 replies
mikevrind's avatar

Never tried it but maybe: DB::table('tags as ta')... you didn't state the table alias.

hillcow's avatar

never mind, it was just that Laravel database aliases work with "AS"

edit: yep, mikevrind that was right, thank you very much!

hillcow's avatar

@mikevrind I am wondering if it is possible to use Eloquent for such complex queries?

mikevrind's avatar

Yes you can also write joins using Eloquent. Works exactly the same :) . You could also simplify your orderBy by using orderByRaw.

Youz's avatar

You should use Eloquent that's provide a good way to interct with your Database :)

Please or to participate in this conversation.