我一直在尝试在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%')))")
$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)
我很确定我错过了什么,但我找不到它是什么.提前致谢.
解决方法:
你可以这样做:
$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%')"
标签:php,laravel
来源: https://codeday.me/bug/20190527/1163452.html