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');
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With