Home > Mobile >  How to combine AND and multiple OR conditions in where clause
How to combine AND and multiple OR conditions in where clause

Time:02-04

I need to create this kind of sql query in Laravel:

SELECT * FROM `list` WHERE `column_A` > 100 AND (`column_B` = 'value_1' OR `column_B` = 'value_2' OR `column_B` = 'value_3' OR ... `column_B` = 'value_n')

The thing is that I need the second part of the condition (following after "AND") to be inserted as an array containing the conditions, i.e.:

$conditions = array(['column_B', '=', 'value_1'], ['column_B', '=', 'value_2'], ['column_B', '=', 'value_3']), ['column_B', '=', 'value_n']);

so I can create each set of conditions separately.

Is there such a way to do this in Laravel Query Builder (no Eloquent please)?

CodePudding user response:

In order to group conditions you have to use a closure, you can read more here: https://laravel.com/docs/8.x/queries#or-where-clauses

\DB::table('list')
    ->where('column_A', '>', 100)
    ->where(function($q) use ($conditions) { 
        foreach ($conditions as $condition) { 
            $q->orWhere(...$condition); 
        }  
    });

CodePudding user response:

Since you need to check one column against multiple values you can simply use whereIn:

->where('column_A', '>', 100)
->whereIn('column_B', ['foo', 'bar', 'baz'])
  •  Tags:  
  • Related