Can Laravel hasOne be used with belongsToMany?

天涯浪子 提交于 2019-12-24 17:28:27

问题


Let's say I have two tables:

Users: id, name, country_id

Countries: id, name

Of course each user can only have one country, but each country is assigned to multiple users.

So would it be safe to have a User model that utilizes hasOne and a Country model that uses belongsToMany method?

Documentation makes it seem like you can't mix and match different types of relationships.


回答1:


What you are describing is actually a One To Many relationship, where one country has many users. Your Country model should utilize a hasMany relationship, while your user would have a belongsTo relationship.




回答2:


@Andy has already answered well.
Anyway, my advice is to always think in the following way to create a One-To-One, One-To-Many, or a Many-To-Many relationship:

  • In the table with the foreign key (if any) use belongsTo
  • In the other table without the foreign key use hasOne or hasMany
  • In any of them have a foreign key, you have a Many To Many relationship and you must use belongsToMany in both of them (you need the pivot table, of course).


来源:https://stackoverflow.com/questions/34598287/can-laravel-hasone-be-used-with-belongstomany

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