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

latz's avatar
Level 3

Do not understand Eloquent with join

I don't know if I can do this with Eloquent.

3 Tables. Example: invoices: (ID, invoicedate, amount, tax....) invoiceitems: (itemid, invoicesID, serviceID, quantity....) services: (serviceid, description, price....) I need a result like [invoice, [invoiceitems]] The foreign keys should be resolved (e.g. invoiceitems.serviceID with services.description)

Is a Join with Eloquent possible or is this the right way? DB::table('xy') ->join('xy', 'xy', '=', 'xy')...

I hope you understand what I mean.

0 likes
2 replies
jlrdw's avatar

Something like this:

$quy = Powner::query()->leftJoin('dc_pets', 'dc_powners.ownerid', '=', 'dc_pets.ownerid')
                ->select('dc_powners.ownerid', 'dc_powners.oname')
                ->selectRaw('count(dc_pets.petid) as countOfPets')
                ->groupby('dc_powners.ownerid')
                ->orderby('dc_powners.oname')
                ->get();

Results basically give:

ownerid, oname, countOfPets

Like:

5|Bob|3
4|Greg|9
2|Rob|1

No different than a normal query, just using QB techniques instead.

1 like
latz's avatar
Level 3

Thank you very much. But I understand that this is not possible with eloquent?

Please or to participate in this conversation.