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

phpxtreme's avatar

Convert Raw SQL to Eloquent

Hello, could you help me convert this SQL query to Eloquent:

SELECT item.id, hired.item_id, hired.quantity - item.quantity as quanity
FROM items item
       join hireds hired on hired.item_id = item.id
WHERE item.quantity > hired.quantity
order by item.id;
0 likes
8 replies
Cronix's avatar

Before converting to Eloquent, you'd need to make an Item and Hired model to represent both of those tables. Have you?

2 likes
jlrdw's avatar

Study docs so you can do things like:

$quy = Powner::query()->leftJoin('dc_pets', 'dc_powners.ownerid', '=', 'dc_pets.ownerid')
                ->select('dc_powners.ownerid', 'dc_powners.oname')->distinct()
                ->selectRaw('max(dc_pets.petid) as maxid')
                ->where('dc_powners.ownerid', '<', 3)
                ->groupby('dc_powners.ownerid')
                ->orderby('dc_powners.oname')
                ->get();

Or study eloquent relations:

https://laravel.com/docs/5.8/eloquent-relationships

Watch the laravel 5.8 from scratch free video series

https://laracasts.com/series/laravel-from-scratch-2018

Yes also:

Before converting to Eloquent, you'd need to make an Item and Hired model to represent both of those tables.

https://laravel.com/docs/5.8/eloquent Explains all that.

1 like
jlrdw's avatar

Then practice some queries. Can take some trial and error to get right.

Eloquent has all query builder methods also, in case you missed that part in the docs.

1 like
phpxtreme's avatar

My final solution...

 $hireds = Hired::query()
            ->select('item.id', 'hired.item_id')
            ->selectRaw('hired.quantity - item.quantity as quanity')
            ->from('items as item')
            ->rightJoin('hireds as hired', 'hired.item_id', '=', 'item.id')
            ->whereRaw('item.quantity < hired.quantity')
            ->orderBy('item.id', 'ASC')
            ->get();
jlrdw's avatar

To place code on the forum, surround the code with three back ticks 3 before and 3 after.

1 like

Please or to participate in this conversation.