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

时间:2022-10-26 09:16:33

I am trying to make a MySQL query inside Laravel.

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

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

I tried the code below

我试过下面的代码

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);
}

But I am getting the following error

但是我收到以下错误

Missing argument 2 for App\Http\Controllers\PatientController::App\Http\Controllers{closure}()

App \ Http \ Controllers \ PatientController :: App \ Http \ Controllers {closure}()缺少参数2

1 个解决方案

#1


1  

You have syntax error in where clause. See this:

你在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);
}

#1


1  

You have syntax error in where clause. See this:

你在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);
}