Home > Blockchain >  Laravel prioritize or operator in relation query (hasMany). How to add parenthesis?
Laravel prioritize or operator in relation query (hasMany). How to add parenthesis?

Time:05-12

The events method in my model returns all related events from the database. The code below is working fine, the only problem is dat it don't prioritze the or. (See orWhereHas)

public function events()
{
    return $this->hasMany(Event::class)
        ->orWhereHas('organisations', function(Builder $query){
            $query->where('organisation_id', $this->id);
        });
}

When I extend the query somewhere else in the code, it goes wrong:

$model->events()->whereNull('some_field')

Because it should prioritize the OR operator. But I don't know how to do that in this case because I am imitating the query from a model relation.

So the question is: how to add parenthesis in the query to prioritize the or operator?

CodePudding user response:

You could move the logic outside the relationship method and use a where/orWhere Closure.

public function events()
{
    return $this->hasMany(Event::class)
}
$model->events()
    ->where(function ($sub) {
        $sub->orWhereHas('organisations', function(Builder $query){
                $query->where('organisation_id', $this->id);
            })
            ->orWhereNull('some_field');
    })
  • Related