如何在Laravel SQL原始查询中使用括号

时间:2022-10-25 08:29:05

I want to build a query where an user need his/her correct username or email and password to login.

我想构建一个查询,用户需要正确的用户名或电子邮件和密码才能登录。

Here is my Laravel query code

这是我的Laravel查询代码

$query = Adminuser::where('password',$password);
$query->orWhere('email',$username);        
$query->where('username',$username);

By using this I got the raw SQL query like

通过使用这个,我得到了原始的SQL查询。

select * from `adminuser` where `password` = $password and `email` = $username or `username` = $username

But I need the raw SQL query like to get the proper result

但是我需要原始的SQL查询来得到正确的结果。

select * from `adminuser` where `password` = $password and (`email` = $username or `username` = $username)

So my question is how to use the parenthesis in my laravel query?

我的问题是如何在laravel查询中使用括号?

Anyone help please ?

任何帮助吗?

2 个解决方案

#1


3  

You will need to use grouping. Please read more: Parameter Grouping (Laravel 4.2).

您将需要使用分组。请阅读更多:参数分组(Laravel 4.2)。

Your query should like this(not tested):

您的查询应该如下(未测试):

EDIT:

编辑:

Model::where(function ($query) use ($password) {
    $query->where('password',$password);
})->where(function ($query) use (email, $password){
    $query->where('email',$email)
          ->orWhere('username',$username);
});

#2


1  

$query = Adminuser::where('password',$password)->where(function($query) use ($username){
$query->orWhere(['email' => $username, 'username' => $username])
})->first();

#1


3  

You will need to use grouping. Please read more: Parameter Grouping (Laravel 4.2).

您将需要使用分组。请阅读更多:参数分组(Laravel 4.2)。

Your query should like this(not tested):

您的查询应该如下(未测试):

EDIT:

编辑:

Model::where(function ($query) use ($password) {
    $query->where('password',$password);
})->where(function ($query) use (email, $password){
    $query->where('email',$email)
          ->orWhere('username',$username);
});

#2


1  

$query = Adminuser::where('password',$password)->where(function($query) use ($username){
$query->orWhere(['email' => $username, 'username' => $username])
})->first();