我想创建一个where子句,它是一个和,带有一个或者列表。这是我的代码:
$searchLoop = array(
'u.Name',
'u.Email',
'n.Name',
'u.PhoneMobile'
);
$text = 'Manager';
$count = 0;
foreach ($searchLoop as $loop) {
$query->where(function ($where) use ($loop, $count, $text) {
if ($count === 0) {
$where->where($loop, 'like', '%' . $text . '%');
} else {
$where->orWhere($loop, 'like', '%' . $text . '%');
}
});
$count++;
}
基于我阅读laravel文档和其他一些搜索,我希望这样翻译:
and (
`u`.`Name` like '%Manager%'
or `u`.`Email` like '%Manager%'
or `n`.`Name` like '%Manager%'
or `u`.`PhoneMobile` like '%Manager%'
)
相反,它转化为:
and (`u`.`Name` like '%Manager%')
and (`u`.`Email` like '%Manager%')
and (`n`.`Name` like '%Manager%')
and (`u`.`PhoneMobile` like '%Manager%')
此外,似乎无论我如何使用$ where->在$ query-> where函数中的位置(我是否只为每个循环执行orWhere等) ,它仍然只有和。
感谢您的帮助。
答案 0 :(得分:5)
感谢所有帮助过的人。我终于能够弄明白这一点,坚持查询函数内部的foreach解决了问题
$query - > where(function($where) use($searchLoop, $text) {
foreach($searchLoop as $count => $loop) {
if ($count === 0) {
$where - > where($loop, 'like', '%'.$text.
'%');
} else {
$where - > orWhere($loop, 'like', '%'.$text.
'%');
}
}
});
答案 1 :(得分:0)
我认为您不需要嵌套查询。这个怎么样? (由Pep Lainez稍微重构)
foreach ($searchLoop as $count => $loop) {
if ($count === 0) {
$query = $query->where($loop, 'like', '%' . $text . '%');
} else {
$query = $query->orWhere($loop, 'like', '%' . $text . '%');
}
}
答案 2 :(得分:0)
这对我来说很好(在laravel 5.4上);
$text = 'Manager';
$test = User::query()
->where('id',1)
->where(function($query)use($text){
$query->where('u.Name','like',"%{$text}%");
$query->orWhere('u.Email','like',"%{$text}%");
$query->orWhere('n.name','like',"%{$text}%");
$query->orWhere('u.PhoneMobile','like',"%{$text}%");
})->toSql();
哪个输出
SELECT *
FROM "users"
WHERE "id" = ?
AND (
"u"."Name" LIKE ?
OR "u"."Email" LIKE ?
OR "n"."name" LIKE ?
OR "u"."PhoneMobile" LIKE ?
)