[英]Laravel: Many To Many relationship with only 2 tables
我试图在一个小的软件中实现标记功能,出于简单原因,我实际上只想使用两个表,就像这样:
items (first table)
- id (int)
- title (string)
- description (string)
item_tag (second "pivot" table)
- item_id (int, foreign key to item.id)
- tag_name (string (!))
(primary_key(item_id, tag_name))
与模型
<?php
class Item extends Eloquent {
protected $fillable = array('title', 'desription');
public function tags() {
return $this->belongsToMany('Tag', 'item_tag', 'item_id', 'tag_name');
}
}
和
<?php
class Tag extends Eloquent {
protected $fillable = array('tag_name');
public function items() {
return $this->belongsToMany('Item', 'item_tag', 'item_id', 'tag_name');
}
}
但是,我似乎无法belongsToMany
正常工作,因为belongsToMany
函数似乎期望使用三个表,而Laravel似乎想要一个tags
表。 我知道,我只使用两个表的计划并不是很优雅,因为它增加了冗余,但是对于我的用例来说还是可以接受的。 那么对此有什么快速解决方案吗?
这不是一个belongsToMany
关系,而是hasMany
。 每个项目都有许多标签。
这种方法的问题在于,如果将来您想更改标签的名称或添加额外的字段(例如描述),则必须使用该标签对所有数据库行进行更新。 拥有一个专用的标签表会容易得多,就像这样:
tags
- id (int)
- name (string)
然后像这样设置数据透视表:
item_tag
- id (int)
- item_id (int)
- tag_id (int)
这样,您可以轻松更改标签的名称,添加额外的列以及类似内容,而无需影响多个条目。
一旦拥有了这三个表(将您所拥有的项目表述为一个表),只要您遵循正确的命名方案,您的belongsToMany
关系就将起作用,您甚至不必指定主键/表的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.