Eloquent/Laravel 三向多对多关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16866999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Eloquent/Laravel Three-way Many-to-Many Relationship
提问by Raolin
I'm brand new to Laravel and Eloquent (and I have minimal experience with ORM in general).
我是 Laravel 和 Eloquent 的新手(总的来说,我对 ORM 的经验很少)。
Let's say I have three database tables:
假设我有三个数据库表:
- Widgets
- Actions
- Users
- 小工具
- 行动
- 用户
I have modelled one junction table that has columns for:
我已经建模了一个连接表,其中包含以下列:
widget_id
action_id
user_id
- timestamp
widget_id
action_id
user_id
- 时间戳
The point of the junction is to keep a log of interactions--take a timestamp every time a user
performs an action
on a widget
. I see how to model a simple many-to-many relationship using Eloquent and have this working fine, but I'm not sure how to model a more complicated three-way relationship.
结点是保持一个日志互动-以时间戳每次user
执行action
上widget
。我看到了如何使用 Eloquent 对简单的多对多关系进行建模并使其工作正常,但我不确定如何对更复杂的三向关系进行建模。
For that matter, even if I had a simply many-to-many relationship (say widget
to action
so there would be a table called action_widget
), how can I add an explicit model for the action_widget
table in Eloquent, for the purpose of keeping track of extra data about each relationship (e.g. a timestamp, a comments field, etc). Or, am I just going about this in a totally wrong way?
对于这个问题,即使我有一个简单的多对一对多的关系(说widget
来action
这样会有一个名为表action_widget
),我怎么可以添加一个明确的模式,为action_widget
雄辩表,用于跟踪额外数据的目的关于每个关系(例如时间戳、评论字段等)。或者,我只是以一种完全错误的方式来解决这个问题?
Being new to ORM, I feel very confined as to what I can do! Does this feeling go away? :p
作为 ORM 的新手,我对自己能做什么感到非常受限!这种感觉会消失吗?:p
回答by Yahia Reyhani
pivot work fine when you have 2 way relation like Categoty<->Article. but if you have 3 way relation i think it's better to have a model called WidgetUserAction.
当您有像 Categoty<->Article 这样的 2 种关系时,pivot 工作正常。但如果你有 3 向关系,我认为最好有一个名为 WidgetUserAction 的模型。
Edit : For these cases the new "hasManyThrough" works fine.
编辑:对于这些情况,新的“hasManyThrough”工作正常。
回答by Franz
Laravel can create the intermediate model automatically. They're called "pivot tables".
Laravel 可以自动创建中间模型。它们被称为“数据透视表”。
I suggest you read this section in the documentation.
我建议您阅读文档中的这一部分。