Eloquent/Laravel Three-way Many-to-Many Relationship

落花浮王杯 提交于 2019-12-22 05:36:12

问题


I'm brand new to Laravel and Eloquent (and I have minimal experience with ORM in general).

Let's say I have three database tables:

  1. Widgets
  2. Actions
  3. Users

I have modelled one junction table that has columns for:

  1. widget_id
  2. action_id
  3. user_id
  4. timestamp

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.

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?

Being new to ORM, I feel very confined as to what I can do! Does this feeling go away? :p


回答1:


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.

Edit : For these cases the new "hasManyThrough" works fine.




回答2:


Laravel can create the intermediate model automatically. They're called "pivot tables".

I suggest you read this section in the documentation.



来源:https://stackoverflow.com/questions/16866999/eloquent-laravel-three-way-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!