2

Contact Model

class Contact extends Model
{
    public function Account()
    {
        return $this->belongsTo('app\Account');
    }
}

Account Model

class Account extends Model
{
    public function Contact()
    {
        return $this->hasMany('app\Contact');
    }
}

I want to get query of all Contacts that have account_name = 'test' or account_city ='test2'.

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

This query shows me all Contacts that have an Account but I want to get only Contacts that have account_name = 'test' or account_city ='test2'

Result of $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
Karl Hill
  • 12,937
  • 5
  • 58
  • 95
paranoid
  • 6,799
  • 19
  • 49
  • 86

2 Answers2

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

I think it will do the trick.

sultania23
  • 322
  • 3
  • 11
2

try this:

$query=Contact::query();
$query->whereHas('Account', function ($q) {
    $q->where(function($query) {
       $query->where('account_city','test2')->orWhere('account_name','test');
    });
});
$query->get();
paranoid
  • 6,799
  • 19
  • 49
  • 86
Jinal Somaiya
  • 1,931
  • 15
  • 29