如何在Laravel中应用Mysql AND / OR子句

时间:2016-05-13 13:05:15

标签: php mysql laravel laravel-5

我正在尝试在Laravel内部进行MySQL查询。

> "select * from users u where (name like
> '%".$request->search_string."%' or email like
> '%".$request->search_string."%') and (user_type=2)";

我尝试了以下代码

public function searchUsers(Request $request){
        $query = DB::table('users as u');
        $query->where('u.user_type',2);
        $query->where(function($query,$request){
            $query->orwhere('u.name','LIKE','%'.$request->search_string.'%');
            $query->orwhere('u.email','LIKE','%'.$request->search_string.'%');
        });
        $result['all_users'] = $query->get();
    return Response::json($result);
}

但是我收到以下错误

  

缺少参数2   应用\ HTTP \控制器\ PatientController ::应用\ HTTP \控制器{闭合}()

1 个答案:

答案 0 :(得分:1)

where子句中存在语法错误。见:

public function searchUsers(Request $request){
        $query = DB::table('users as u');
        $query->where('u.user_type',2);
        $query->where(function($query)use($request){ // Here  is the change
                    //  ^^ Pass only one parameter to closure function and pass `$request` in `use` function
            $query->orwhere('u.name','LIKE','%'.$request->search_string.'%');
            $query->orwhere('u.email','LIKE','%'.$request->search_string.'%');
        });
        $result['all_users'] = $query->get();
    return Response::json($result);
}