Shateel Ahmed Shateel Ahmed - 2 months ago 10
MySQL Question

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);
}
}

Answer

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();