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

ssquare's avatar

Refactoring DB Select sub query

What is the best way to call the below mentioned DB:Select query. I don't want to use eloquent. How can I bind parameter in the subquery.

DB::select('SELECT * FROM   
      (  
       SELECT A.id as id,A.name,C.category_name 
       FROM alerts AS A 
       LEFT JOIN categories as C 
       ON A.category_id = C.id
       where A.id < '. $OldLowestID.'
       order by id asc  
       limit '.$pagesize.'
       ) as myAlias   
  ORDER BY id ASC');
0 likes
1 reply
bobbybouwmann's avatar

You can do it like so

DB::select('SELECT * FROM   
      (  
       SELECT A.id as id,A.name,C.category_name 
       FROM alerts AS A 
       LEFT JOIN categories as C 
       ON A.category_id = C.id
       where A.id < ?
       order by id asc  
       limit ?
       ) as myAlias   
  ORDER BY id ASC', [$OldLowestID, $pagesize]);

Basically just replace each variable with a question and add them in the array as a second argument. Make sure you're doing that in the correct order.

Please or to participate in this conversation.