Andy
Andy

Reputation: 25

Laravel pivot table with 3 relationships

I'm trying to figure out how to set up my relationship using a pivot table with three different relationships.

users
- id
- username

products
- id
- name

tags
- id
- user_id
- name

user_products
- user_id
- tag_id
- product_id

When using the "Product" model, I would like to be able to pull all the associated tags. I'm currently able to pull the "user_products" object, but I would like to know how to pull the actual tag object in stead.

Models:

class User {
    public function tags()
    {
        return $this->hasMany('UserTag');
    }
}

class Product  {

    public function user()
    {
        return $this->belongsTo('User','user_products','product_id','user_id');
    }

    public function tags()
    {
        ????
    }
}

Upvotes: 0

Views: 1107

Answers (1)

ounos
ounos

Reputation: 126

return $this->belongsTo('User','user_products','product_id','user_id')
->withPivot('tag_id')
->join('tags', 'tags.id', '=', 'user_products.tag_id')
->select(...);

Something like this should work fine.

Upvotes: 1

Related Questions