Q8root
Q8root

Reputation: 1355

Using hasManyThrough in Relationship query

I have the following tables :

users
id|name|username

Areas
id|name

user_area
id|user_id|area_id

Buildings
id|name|area_id

In User models i want to call query that every users have his assigned areas and his assigned areas has many buildings, so i created a method in User model that query the user assigned buildings. In App\User Model:

 public function areas()
    {
        return $this->belongsToMany('App\Area','area_user');
    }
  public function UserBuildings(){
        return $this>hasManyThrough('App\Building','App\Area','user_id','area_id');
    }

In App\Area Model:

public function users(){
        return $this->belongsToMany('App\User','area_user','area_id','user_id');
    }

    public function buildings(){
        return $this->hasMany('App\Building');
    }

In App\Building Model:

public function areas(){
        $this->belongsTo('App\Area');
    }

How can i structure a relationship method in User Model that get the user assigned buildings.

Thanks

Upvotes: 1

Views: 716

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163758

You can't use hasManyThrough here, but you can use nested whereHas() to get all buildings assigned to authenticated user:

Building::whereHas('area', function ($q) {
    $q->whereHas('users', function ($q) {
        $q->where('id', auth()->id());
    });
})->get();

Also, you should rename areas relationship to area in Building model, since each building belongs to only one area.

Upvotes: 2

Related Questions