lundi 26 septembre 2016

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire