问题
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
orhasMany
- 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