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

NoLAstNamE's avatar

Converting MySQL query to Eloquent

I have a MySQL query which is working fine, but I want to convert it into an Eloquent query, is this possible?

This query will get the sum of quantity by product from all orders and show it's current stock.

Query:

SELECT p.name, SUM(op.quantity) AS quantity, p.stock 
FROM  `orders` o 
JOIN 
      order_items op
      ON op.order_id = o.id
LEFT JOIN products p ON p.id = op.item_id      
WHERE o.status = 'Completed'
GROUP BY p.id
ORDER BY p.name;
0 likes
2 replies
laracoft's avatar
laracoft
Best Answer
Level 27

@whoami1509

DB::selectRaw('products.name, SUM(order_items.quantity) AS quantity, products.stock')
    ->from('orders')
    ->join('order_items', 'order_items.order_id', '=', 'orders.id')
    ->leftJoin('products', 'products.id', '=', 'order_items.item_id')
    ->where('order.status', 'Completed')
    ->groupBy([
        'products.id', 'products.name',
    ])
    ->all();	
1 like

Please or to participate in this conversation.