Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel hasManyThrough with constraint on intermediate Model

Tags:

php

laravel

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');
}
like image 874
user481779 Avatar asked Nov 15 '25 11:11

user481779


1 Answers

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);
}
like image 167
Fiete Avatar answered Nov 18 '25 04:11

Fiete



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!