代码之家  ›  专栏  ›  技术社区  ›  paranoid

在Laravel 5中的wherehas()中有多个orwhere()。

  •  1
  • paranoid  · 技术社区  · 6 年前

    接触模型

    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 但我只想联系 帐户“name='测试' 帐户“城市=”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 回复  |  直到 6 年前
        1
  •  1
  •   paranoid    6 年前

    试试这个:

    $query=Contact::query();
    $query->whereHas('Account', function ($q) {
        $q->where(function($query) {
           $query->where('account_city','test2')->orWhere('account_name','test');
        });
    });
    $query->get();
    
        2
  •  2
  •   sultania23    6 年前
     $query=Contact::query();
     $query  =  $query->whereHas('Account', function ($q)  {
           $q->orwhere('account_name',test');
           $q->orwhere('account_city','test2');
     });
     $query->get;
    

    我想它会起作用的。

    推荐文章