有没有办法通过 orWhereIn 参数一个一个地循环查询构建器?
Is there a way to loop query builder through orWhereIn parameters one by one?
我想知道是否有循环的方法->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);
也许你可以这样做:
->orWhereIn('parent_id', [$data1, $data2, $data3, $data4])
前提是所有这些都不是子数组。如果他们在尝试之前将它们合并到一个数组中。
您可以只使用 whereIn
函数来实现该结果,而不是循环查询,只需循环您传递给 whereIn
函数的数组作为第二个参数。
$parent_ids = [];
foreach($some_data as $data) {
// [add ids in parent_ids here]
}
$data= data::query()->whereIn('parent_id', $parent_ids);
或者,如果您想在查询构建器中循环,您可以使用嵌套的 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);
}
});
结果SQL:
SELECT * FROM table WHERE (parent_id = 1 OR parent_id = 2 OR parent_id = 3 ... );
我想知道是否有循环的方法->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);
也许你可以这样做:
->orWhereIn('parent_id', [$data1, $data2, $data3, $data4])
前提是所有这些都不是子数组。如果他们在尝试之前将它们合并到一个数组中。
您可以只使用 whereIn
函数来实现该结果,而不是循环查询,只需循环您传递给 whereIn
函数的数组作为第二个参数。
$parent_ids = [];
foreach($some_data as $data) {
// [add ids in parent_ids here]
}
$data= data::query()->whereIn('parent_id', $parent_ids);
或者,如果您想在查询构建器中循环,您可以使用嵌套的 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);
}
});
结果SQL:
SELECT * FROM table WHERE (parent_id = 1 OR parent_id = 2 OR parent_id = 3 ... );