Laravel 5 中 whereHas() 中的多个 orWhere()
Multiple orWhere() in whereHas() in Laravel 5
联系模特
class Contact extends Model
{
public function Account()
{
return $this->belongsTo('app\Account');
}
}
账户模型
class Account extends Model
{
public function Contact()
{
return $this->hasMany('app\Contact');
}
}
我想查询所有具有 account_name = 'test'
或 account_city ='test2'
的联系人。
$query = Contact::query();
$query->whereHas('Account', function ($q) {
$q->orwhere('account_name' ,'=', 'test');
$q->orwhere('account_city','=','test2');
});
$query->get;
此查询向我显示了具有 Account
的所有联系人,但我只想获取具有 account_name = 'test'
或 account_city ='test2'
的联系人
$query->tosql();
的结果
select * from `contacts` where exists (select * from `accounts` where (`contacts`.`account_id` = `accounts`.`id` or (`account_name` = ? or `account_city` = ?)) and `accounts`.`deleted_at` is null) and `contacts`.`deleted_at` is null
$query=Contact::query();
$query = $query->whereHas('Account', function ($q) {
$q->orwhere('account_name',test');
$q->orwhere('account_city','test2');
});
$query->get;
我认为它会成功。
试试这个:
$query=Contact::query();
$query->whereHas('Account', function ($q) {
$q->where(function($query) {
$query->where('account_city','test2')->orWhere('account_name','test');
});
});
$query->get();
联系模特
class Contact extends Model
{
public function Account()
{
return $this->belongsTo('app\Account');
}
}
账户模型
class Account extends Model
{
public function Contact()
{
return $this->hasMany('app\Contact');
}
}
我想查询所有具有 account_name = 'test'
或 account_city ='test2'
的联系人。
$query = Contact::query();
$query->whereHas('Account', function ($q) {
$q->orwhere('account_name' ,'=', 'test');
$q->orwhere('account_city','=','test2');
});
$query->get;
此查询向我显示了具有 Account
的所有联系人,但我只想获取具有 account_name = 'test'
或 account_city ='test2'
$query->tosql();
select * from `contacts` where exists (select * from `accounts` where (`contacts`.`account_id` = `accounts`.`id` or (`account_name` = ? or `account_city` = ?)) and `accounts`.`deleted_at` is null) and `contacts`.`deleted_at` is null
$query=Contact::query();
$query = $query->whereHas('Account', function ($q) {
$q->orwhere('account_name',test');
$q->orwhere('account_city','test2');
});
$query->get;
我认为它会成功。
试试这个:
$query=Contact::query();
$query->whereHas('Account', function ($q) {
$q->where(function($query) {
$query->where('account_city','test2')->orWhere('account_name','test');
});
});
$query->get();