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

DennisHermannsen's avatar

Rewrite SQL query

Hello. I'm trying to update some old code we have. I need to rewrite the following query: SELECT DISTINCT tblclients.id,tblclients.firstname,tblclients.lastname FROM tblclients, tblhosting WHERE tblclients.status="Active" AND tblclients.id=userid AND tblhosting.domainstatus="Active" AND tblhosting.server=1

I'm a newb at MySQL, so this is a difficult problem for me. I've heard about joins and guess I might need to use that, but at the moment I'm stuck trying to figure out how.

0 likes
4 replies
DennisHermannsen's avatar

I want to use joins provided by eloquent. I have this at the moment:

Capsule::table('tblhosting')
    ->where('domainstatus', 'Active')
    ->join('tblclients', 'tblhosting.userid', '=', 'tblclients.id')
    ->distinct()
    ->get(['tblclients.id']);

which helps me get the relevant client IDs that have an active product. I'm just confused as to how to port that query into eloquent.

DennisHermannsen's avatar

I think I might have it now.

Capsule::table('tblhosting')
    ->where('domainstatus', 'Active')
    ->join('tblclients', 'tblhosting.userid', '=', 'tblclients.id')
    ->join('tblservers', 'tblservers.id', '=', 'tblhosting.server')
    ->where('tblservers.id', '1')
    ->distinct()
    ->get(['tblclients.id']);

Does that look correct at all compared to the MySQL query?

jlrdw's avatar

A QB or eloquent query can take some trial and error just like a regular sql query can.

Just remember an eloquent query converts to a normal sql query and run time.

Please or to participate in this conversation.