【问题标题】:Laravel pivot table with 3 relationships具有 3 个关系的 Laravel 数据透视表
【发布时间】:2014-12-12 21:49:14
【问题描述】:

我试图弄清楚如何使用具有三种不同关系的数据透视表来设置我的关系。

users
- id
- username

products
- id
- name

tags
- id
- user_id
- name

user_products
- user_id
- tag_id
- product_id

当使用“产品”模型时,我希望能够提取所有关联的标签。我目前能够拉取“user_products”对象,但我想知道如何取而代之拉取实际的标签对象。

型号:

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()
    {
        ????
    }
}

【问题讨论】:

标签: laravel eloquent


【解决方案1】:
return $this->belongsTo('User','user_products','product_id','user_id')
->withPivot('tag_id')
->join('tags', 'tags.id', '=', 'user_products.tag_id')
->select(...);

这样的东西应该可以正常工作。

【讨论】:

    猜你喜欢
    • 2014-09-16
    • 1970-01-01
    • 2019-01-29
    • 2016-11-27
    • 2017-07-22
    • 2020-08-22
    • 2014-09-29
    • 1970-01-01
    • 2014-08-26
    相关资源
    最近更新 更多