Totallama
Totallama

Reputation: 448

How to combine AND and multiple OR conditions in where clause

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)?

Upvotes: 0

Views: 1707

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272096

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'])

Upvotes: 1

Vadim Sirbu
Vadim Sirbu

Reputation: 681

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); 
        }  
    });

Upvotes: 1

Related Questions