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

pafait's avatar

query

HI every one please can some help me write this SQL query into laravel eloquent

 SELECT SUM(price) FROM (
SELECT COUNT(STOCK_ID)*Price 
    FROM STOCK ST INNER JOIN PRODUCT PDT ON PDT.PROD_ID=ST.PROD_ID  
        WHERE PROD_NAME='PENCIL' GROUP BY STOCK_ID LIMIT 6 ) TB

This is what i try out but am messing the whole ting

  DB::(table_stock)
  ->where(['tbl_stock.product_id', $product_id]) 
  ->join('tbl.product','stock.product_id', '=' 'tbl_product.product_id')
  ->count(stock_id)*price
0 likes
4 replies
tykus's avatar

Just DB::raw() your working query.

pafait's avatar

Hello @tykus thanks your reply but please can you be explicit i don't understand what your saying. Thanks

tykus's avatar
DB::select(DB::raw("
    SELECT SUM(price) FROM (
        SELECT COUNT(stock_id)*Price 
        FROM stock st 
        INNER JOIN product pdt ON pdt.prod_id = st.prod_id  
            WHERE prod_name = 'PENCIL'
        GROUP BY stock_id
        LIMIT 6
    ) 
"));
spekkionu's avatar

Yeah, if you aren't returning instances of eloquent models you gain nothing from using the builder to run the query. In fact by running the raw query you skip the step of converting the builder into a query so it should be a tiny bit faster.

Please or to participate in this conversation.