我一直在尝试在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%')))")
我遵循这个帖子(Eloquent WHERE LIKE clause with multiple columns)并且它工作正常,但只有两列Ej:
$students = student::where(user_id, Auth::id())
->whereRaw('concat(name," ",last_name) like ?', "%{$q}%")
->paginate(9);
但是如果我添加两列以上,那么结果变量总是为空,无论变量$ q中的内容是否与一列或多列相匹配:
$students = student::where(user_id, Auth::id())
->whereRaw('concat(name," ",last_name," ",email) like ?', "%{$q}%")
->paginate(9)
我很确定我错过了什么,但我找不到它是什么。提前谢谢。
答案 0 :(得分:8)
您可以这样做:
$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);
上述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%')"