Robin C Samuel
Robin C Samuel

Reputation: 1225

Adding 'orWhere' to laravel eloquent model relationship

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 where notifications.receiver_id = 3 and notifications.receiver_id is not null and notifications.receiver_type = User or type = 2 and status = 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 and notifications.receiver_id is not null and notifications.receiver_type = User or type = 2 ) and status = 1

Upvotes: 0

Views: 1071

Answers (2)

kapilpatwa93
kapilpatwa93

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

SteD
SteD

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

Related Questions