如何在laravel 5.3中使用OR和AND和where子句?

时间:2018-06-14 07:57:15

标签: laravel laravel-5.3

- 我想使用的查询:

select * from users where (email like '%email@email.com%' OR username like 'myusername') AND (password like '%1234@abcde%')

- 我上面查询的laravel代码是:

$getInfo = Users::where('password','like','%'.$request->password.'%')
            ->where(function($query){
                $query->where('email','like','%'.$request->username.'%')
                ->orWhere('username','like','%'.$req->username.'%');
            })->get();

我收到错误未定义变量:请求

2 个答案:

答案 0 :(得分:2)

您需要将$request传递给您的关闭函数,例如use ($request)

$getInfo = Users::where('password','like','%'.$request->password.'%')
            ->where(function($query) use ($request){
                $query->where('email','like','%'.$request->username.'%')
                ->orWhere('username','like','%'.$req->username.'%');
            })->get();

使用两边的通配符(%)搜索用户详细信息也不是一个好主意,它应该只是like没有通配符或只是使用相等比较=

答案 1 :(得分:1)

$getInfo = Users::where('password','like','%'.$request->password.'%')
            ->where(function($query) use ($request){
                $query->where('email','like','%'.$request->username.'%')
                ->orWhere('username','like','%'.$request->username.'%');
            })->get();

您可以使用use ($request)将变量封闭。

您还有一个拼写错误

更改

->orWhere('username','like','%'.$req->username.'%');

->orWhere('username','like','%'.$request->username.'%');