【问题标题】:Three-way pivot Table Laravel三向枢轴表 Laravel
【发布时间】:2020-07-29 14:50:06
【问题描述】:

我很难在我的 Laravel 应用中连接三个模型。模型是瓶子、标签和精神。我想获取基于bottle_id 和spirit_id 的所有标签,所以我创建了一个数据透视表来存储Bottle-Label-Spirit 之间的关系。请看下面我当前的设置。

数据库

+---------+--------+---------+-------------------------+
| bottles | labels | spirits | bottle_label_spirit     |
+---------+--------+---------+-------------------------+
| id      | id     | id      | id                      |
| name    | name   | name    | bottle_id               |
|         |        |         | label_id                |
|         |        |         | spirit_id               |
|         |        |         | created_at              |
|         |        |         | updated_at              |
+---------+--------+---------+-------------------------+

bottle_label_spirit 是我的数据透视表

瓶类

class Bottle extends Model
{
    public function labels() {
        return $this->belongsToMany(Label::class)->withTimestamps();
    }

    public function spirits() {
        return $this->belongsToMany(Spirit::class)->withTimestamps();
    }
}

标签类

class Label extends Model
{
    public function bottles() {
        return $this->belongsToMany(Bottle::class)->withTimestamps();
    }

    public function spirits() {
        return $this->belongsToMany(Spirit::class)->withTimestamps();
    }
}

精神类

class Spirit extends Model
{

    public function labels() {
        return $this->belongsToMany(Label::class)->withTimestamps();
    }

    public function bottles() {
        return $this->belongsToMany(Bottle::class)->withTimestamps();
    }
}

问题

所以我的问题是:

  • 这是处理manyToMany 关系的正确方法吗?
  • 如果是,我如何获取所有 bottle_id = 1 和 spirit_id = 1 的标签

【问题讨论】:

    标签: php laravel eloquent pivot-table


    【解决方案1】:

    您不需要第四张桌子,您可以使用hasManyThrough 完成所有这些操作。这将允许您查询远距离关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2020-05-06
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      相关资源
      最近更新 更多