Reputation: 1225
I have a model relation like the below one in User
model,
public function notifications(){
return $this->morphMany('App\Notification','receiver')
->orWhere('type', 2);
}
This works well if there are no other conditions. But if $user
is an instance of User
and i call like, $user->notifications->where('status', 1);
,
query condition becomes,
select * from
notifications
wherenotifications
.receiver_id
= 3 andnotifications
.receiver_id
is not null andnotifications
.receiver_type
= User ortype
= 2 andstatus
= 1
here the problem is, the final condition is working as an OR
since i'm not able to group the relation's conditions. Therefore, even if the base relationship condition fails, but just the status & type
fields match, it will fetch that record.
What i need is to add a parenthesis before the first where and close after the relation conditions, so that any other where condition applied will not affect the base query.
What i need:
select * from
notifications
where (notifications
.receiver_id
= 3 andnotifications
.receiver_id
is not null andnotifications
.receiver_type
= User ortype
= 2 ) andstatus
= 1
Upvotes: 0
Views: 1071
Reputation: 4411
Try this..
public function notifications(){
return $this->where(function($query){
$query->morphMany('App\Notification','receiver')
->orWhere('type', 2);
})
}
Replace your code with this code in Model
Hope this works
Upvotes: 0
Reputation: 14027
Check out Parameter Grouping.
Something like this:
Notifications::where('receveier_id', '=', 3)
->whereNotNull('receveier_id')
->where(function ($query) {
$query->where('receiver_type', '=', 'User')
->orWhere('type', '=', 2);
})
->where('status', '=', 1);
Upvotes: 1