Laravel Eloquent Query Using WHERE with OR AND OR?
How do I say WHERE (a = 1 OR b =1 ) AND (c = 1 OR d = 1)
For more complicated queries am I supposed to use raw SQL?
Make use of Logical Grouping (Laravel 7.x/4.2). For your example, it'd be something like this:
Model::where(function ($query) {
$query->where('a', '=', 1)
->orWhere('b', '=', 1);
})->where(function ($query) {
$query->where('c', '=', 1)
->orWhere('d', '=', 1);
});
If you want to use parameters for a,b,c,d in Laravel 4
Model::where(function ($query) use ($a,$b) {
$query->where('a', '=', $a)
->orWhere('b', '=', $b);
})
->where(function ($query) use ($c,$d) {
$query->where('c', '=', $c)
->orWhere('d', '=', $d);
});
if you want to use parentheses in laravel 4 and don't forget return
In Laravel 4 (at least) you need to use $a, $b in parentheses as in the example
$a = 1;
$b = 1;
$c = 1;
$d = 1;
Model::where(function ($query) use ($a, $b) {
return $query->where('a', '=', $a)
->orWhere('b', '=', $b);
})->where(function ($query) use ($c, $d) {
return $query->where('c', '=', $c)
->orWhere('d', '=', $d);
});
This is my result:
Incase you're looping the OR conditions, you don't need the the second $query->where from the other posts (actually I don't think you need in general, you can just use orWhere in the nested where if easier)
$attributes = ['first'=>'a','second'=>'b'];
$query->where(function ($query) use ($attributes)
{
foreach ($attributes as $key=>value)
{
//you can use orWhere the first time, doesn't need to be ->where
$query->orWhere($key,$value);
}
});