【发布时间】: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