Laravel 5中whereHas()中的多个orWhere()

时间:2019-01-15 12:04:00

标签: laravel laravel-5 eloquent laravel-query-builder wherehas

联系方式

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

2 个答案:

答案 0 :(得分:2)

 $query=Contact::query();
 $query  =  $query->whereHas('Account', function ($q)  {
       $q->orwhere('account_name',test');
       $q->orwhere('account_city','test2');
 });
 $query->get;

我认为它将成功。

答案 1 :(得分:1)

尝试一下:

$query=Contact::query();
$query->whereHas('Account', function ($q) {
    $q->where(function($query) {
       $query->where('account_city','test2')->orWhere('account_name','test');
    });
});
$query->get();