'Is there a way to loop query builder through orWhereIn parameters one by one?
I was wondering if there's a way to loop ->OrWhereIn('parent_id', $data1,2,3,4,5)?
$data= data::query()
->where('parent_id', $this->id)
->orWhereIn('parent_id', $data1)
->orWhereIn('parent_id', $data2)
->orWhereIn('parent_id', $data3)
->orWhereIn('parent_id', $data4);
Solution 1:[1]
You can use just whereIn function to achieve that result and instead of looping queries, just loop the array you pass whereIn function as second parameter.
$parent_ids = [];
foreach($some_data as $data) {
// [add ids in parent_ids here]
}
$data= data::query()->whereIn('parent_id', $parent_ids);
Or if you want to loop in query builder you can use nested where:
$parent_ids = [1, 2, 3, 4, $data];
$data= data::query()
->where(function($q) use ($parent_ids) {
foreach($parent_ids as $id) {
$q->orWhere('parent_id', $id);
}
});
Result SQL:
SELECT * FROM table WHERE (parent_id = 1 OR parent_id = 2 OR parent_id = 3 ... );
Solution 2:[2]
Maybe you could something like this:
->orWhereIn('parent_id', [$data1, $data2, $data3, $data4])
Provided all of these are not subarrays. If they are merge them into a single array before trying this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Malkhazi Dartsmelidze |
| Solution 2 | Sachin Bahukhandi |
