laravel 具有两列以上的雄辩 WHERE LIKE 子句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45776650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:31:32  来源:igfitidea点击:

Eloquent WHERE LIKE clause with more than two columns

phplaravel

提问by Oscar Mu?oz

I've been trying to do a query in Laravel that in raw SQL will be like this

我一直在尝试在 Laravel 中进行查询,原始 SQL 将是这样的

"SELECT * FROM students WHERE (((students.user_id)=$id) AND (((students.name) Like '%$q%') OR ((students.last_name) Like '%$q%') OR ((students.email) Like '%$q%')))")

I follow this thread (Eloquent WHERE LIKE clause with multiple columns) and it worked fine, but only with two columns Ej:

我遵循这个线程(带有多个列的 Eloquent WHERE LIKE 子句)并且它工作正常,但只有两列 Ej:

$students = student::where(user_id, Auth::id())
         ->whereRaw('concat(name," ",last_name) like ?', "%{$q}%")
         ->paginate(9);

But if I add more than two columns then the resultant variable is always empty, no matter if what is in the variable $q match with one or more columns:

但是如果我添加两列以上,那么结果变量总是为空的,无论变量 $q 中的内容是否与一列或多列匹配:

$students = student::where(user_id, Auth::id())
         ->whereRaw('concat(name," ",last_name," ",email) like ?', "%{$q}%")
         ->paginate(9)

I am pretty sure I am missing something but i can't find what it is. Thanks in advance.

我很确定我遗漏了一些东西,但我找不到它是什么。提前致谢。

回答by mbozwood

You can do something like this:

你可以这样做:

$students = student::where('user_id', Auth::id())->where(function($query) use ($q) {
    $query->where('name', 'LIKE', '%'.$q.'%')
        ->orWhere('last_name', 'LIKE', '%'.$q.'%')
        ->orWhere('email', 'LIKE', '%'.$q.'%');
})->paginate(9);

The above Eloquent will output SQL similar to

上面的 Eloquent 会输出类似的 SQL

"SELECT * FROM students WHERE students.user_id = $id AND (students.name like '%$q%' OR students.last_name Like '%$q%' OR students.email Like '%$q%')"