Shateel Ahmed
Shateel Ahmed

Reputation: 1334

Retrieve a many-to-many relation through one to many relation

I have a poster that can have one user. The poster can have many tags and a tag can have many posters. Now I would like to retrieve all the distinct tags that were used in the posters created by a specific user. I am using laravel, so, the ORM is eloquent. If someone could provide me a solution using eloquent, it would be much appreciated. I only want to retrieve the tags.
The User Class:

class User extends Model {
    public function posters() {
        return $this->hasMany(Poster::class);
    }
}

The Poster Class:

class Poster extends Model {
    public function user() {
        return $this->belongsTo(User::class);
    }
    public function tags() {
        return $this->belongsToMany(Tag::class);
    }
}

The Tag Class:

class User extends Model {
    public function posters() {
        return $this->belongsToMany(Poster::class);
    }
}

Upvotes: 1

Views: 40

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

whereHas method allows searching records by attributes of related models. It works with nested relations as well, so you could use it to search for all tags used by given user.

The following should do the trick:

$tags = Tag::whereHas('posters.user', function($query) {
  $query->whereId($userId);
})->get();

Upvotes: 1

Related Questions