I have a trouble group multi conditions on laravel version 8
$filters['house_year'] = ["0_5","10_20"]
$this->model = ...// Properties model
$this->model = $this->model->where(function ($query) use ($filters) {
foreach ($filters['house_year'] as $filter) {
switch ($filter) {
case "0_5":
$query = $query->where('house_year', '>=', 0);
$query = $query->where('house_year', '<', 5);
break;
case "5_10":
$query = $query->where('house_year', '>=', 5);
$query = $query->where('house_year', '<', 10);
break;
case "10_20":
$query = $query->where('house_year', '>=', 10);
$query = $query->where('house_year', '<', 20);
break;
default:
$query = $query->where('house_year', '>=', 20);
break;
}
}
return $query;
});
$this->model = $this->model->where('status', 1);
...
How to fix it for this result:
SELECT *
FROM properties
WHERE ((house_year >= 0 AND house_year < 5) OR (house_year >= 10 AND house_year < 20))
AND status = 1
CodePudding user response:
try this
$query->orWhere(function($q){
$query = $query->where('house_year', '>=', 0);
$query = $query->where('house_year', '<', 5);
})
CodePudding user response:
Use something like this:
$data = Property::where('status', 1)
->where(function ($query) {
return $query
->whereBetween('house_year', [0, 5])
->orWhereBetween('house_year', [10, 20]);
})
->get();
Alternatively, if it would include the last positions (AFAIK it wouldn't), you can use kind of this:
$data = Property::where('status', 1)
->where(function ($query) {
return $query
->where([
['house_year', '>=', 0],
['house_year', '<', 5],
])
->orWhereBetween([
['house_year', '>=', 10],
['house_year', '<', 20],
]);
})
->get();
Note: for this example i've used "Property" model, so you can edit that as for your code requirements.