Ad

Laravel HasManyThrough With Constraint On Intermediate Model

- 1 answer

Hi I have the following relationship between my entities.

User
  - id
  - other stuff
NeighborhoodFilter
  - id
  - userId
  - neighborhoodId
  - isActive
Neighborhood
  - id
  - other stuff

I want to write a method for my User object that will return all Neighborhoods the User is a member of which is indicated by isActive = 1 in NeighborhoodFilter.

I have tried the following but I do not know where to put the constraint 'isActive=1'. Any ideas?

public function neighborhoods()
{
    return $this->hasManyThrough('Neighborhood', 'NeighborhoodFilter', 'userId', 'id');
}
Ad

Answer

If you have a relationship between Neighborhood and NeighborhoodFilter from Neighborhood you can use the whereHas function.

public function neighborhoods()
{
    return $this->hasManyThrough('Neighborhood', 'NeighborhoodFilter', 'userId', 'id')->whereHas('neighborhoodFilters', function($q){
        $q->where('isActive', 1);
    });
}

Otherwise you can use the belongsToMany relation and the wherePivot function.

public function neighborhoods()
{
    return $this->belongsToMany('Neighborhood', 'neighborhood_filters', 'user_id', 'neighbor_id')->wherePivot('isActive', 1);
}
Ad
source: stackoverflow.com
Ad