skip to Main Content

How to use WHERE NOT IN in DB:raw Laravel?

Here’s my sample code

$query = DB::select(DB::raw("... WHERE ID NOT IN (:ids) ..", array( 'ids' => "1,2,3" )));

I also tried this

$ids = "'1','2','3'";
$query = DB::select(DB::raw("... WHERE ID NOT IN (:ids) ..", array( 'ids' => $ids )));

3

Answers


  1. Chosen as BEST ANSWER

    Got it. Thank you for your answers, but I use this solution:

    $ids = [1,2,3];
    //ids = [''] if ids is empty
    $bindStr = trim(str_repeat('?,',count($ids)),',');
    $query = DB::select(DB::raw("... WHERE ID NOT IN ({$bindStr})"), $ids);
    

  2. You would need to do use setBindings to bind your params like below

    $query = DB::select(DB::raw("... WHERE ID NOT IN (:ids) .."))
        ->setBindings(['ids' => $ids]);
    

    Answer based on docs https://laravel.com/api/10.x/Illuminate/Database/Query/Builder.html#method_setBindings

    Login or Signup to reply.
  3. I suppose the error, "Unknown column ‘ids’ in ‘where clause’", suggests that the database engine is treating ‘ids’ as a column name rather than as a parameter placeholder.

    The below change can probably work:

    $query = DB::select(DB::raw("... WHERE ID NOT IN (?)"));
    $results = $query->setBindings([$ids]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search