我有一个像这样的Laravel查询,但是我得到了这样的错误
未定义的变量:关键字
$bookings = DB::table('bookings')
->leftJoin('users', 'bookings.manager_id', '=', 'users.id')
->leftJoin('projects', 'bookings.pr_project_id', '=', 'projects.id')
->leftJoin('resources', 'bookings.pr_resource_id', '=', 'resources.id')
->Where('unavailable','=','0')
->orWhere(function ($query) {
$query->Where('users.name', 'LIKE', "%$keyword%")
->Where('projects.project_name', 'LIKE', "%$keyword%")
->Where('resources.r_name', 'LIKE', "%$keyword%");
})
->orderBy('bookings.pr_working_date', 'desc')
->paginate($perPage);
现在下面查询如何在Laravel中进行转换
select * from bookings left join users on bookings.manager_id=users.id left join projects on bookings.pr_project_id=projects.id left join resources on bookings.pr_resource_id=resources.id where unavailable='0' AND (users.name like '%One Web Series%' or projects.project_name like '%One Web Series%' or resources.r_name like '%One Web Series%')
答案 0 :(得分:4)
你需要像这样add the use()
将变量传递给闭包范围:
function ($query) use($keyword) {
答案 1 :(得分:3)
使用use()
-
$bookings = DB::table('bookings')
->leftJoin('users', 'bookings.manager_id', '=', 'users.id')
->leftJoin('projects', 'bookings.pr_project_id', '=', 'projects.id')
->leftJoin('resources', 'bookings.pr_resource_id', '=', 'resources.id')
->Where('unavailable','=','0')
->orWhere(function ($query) use($keyword){
$query->Where('users.name', 'LIKE', "%$keyword%")
->Where('projects.project_name', 'LIKE', "%$keyword%")
->Where('resources.r_name', 'LIKE', "%$keyword%");
})
->orderBy('bookings.pr_working_date', 'desc')
->paginate($perPage);
答案 2 :(得分:1)
您可以使用use关键字将必要的变量从父作用域传递到闭包中。 (即)
Where(function ($query) use($keyword)