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
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();