嵌套在一个where-Laravel中的orwhere
我需要在Laravel6中构建一个查询,该查询在一个where查询中嵌套了where。 例如: 从示例中选择*,其中k=5和((i=1和j=2)或(i=3和j=4)或(i=5和j=4)…) 我试过下面的代码嵌套在一个where-Laravel中的orwhere,laravel,where-clause,Laravel,Where Clause,我需要在Laravel6中构建一个查询,该查询在一个where查询中嵌套了where。 例如: 从示例中选择*,其中k=5和((i=1和j=2)或(i=3和j=4)或(i=5和j=4)…) 我试过下面的代码 $getItems = $getItems->where(function ($query) use($codes,$cID) { $query->orWhere(function ($query1)
$getItems = $getItems->where(function ($query) use($codes,$cID) {
$query->orWhere(function ($query1) use ($codes, $cID) {
foreach($codes[$cID] as $code) {
$query1
->where('code', $code)
->where('cid', $cID);
}
});
});
但结果是错误的
and (("code" = ? and "cid" = ?)) and (("code" = ? and "cid" = ?)) and (("code" = ? and "cid" = ?))....
我不明白为什么它在每个foreach循环中添加2个括号,为什么它添加“and”而不是“or”。
关于如何构建此功能有什么建议吗?您应该有如下结构:
Model::where('k', 5)->where(function($q){
$q->orWhere(function($q){
$q->where('i', 1)->where('j', 2);
})->orWhere(function($q){
$q->where('i', 3)->where('j', 4);
})->orWhere(function($q){
$q->where('i', 5)->where('j', 4);
});
})->toSql();
> select * from `table` where `k` = ? and ((`i` = ? and `j` = ?) or (`i` = ? and `j` = ?) or (`i` = ? and `j` = ?))
因此,您的查询应该是:
$getItems->where('k', 5)
->where(function ($query) use($codes, $cID) {
foreach($codes[$cID] as $code) {
$query->orWhere(function ($query1) use ($code, $cID) {
$query1->where('code', $code)->where('cid', $cID);
});
}
});
这回答了你的问题吗?