zen
zen

Reputation: 1165

Can Laravel hasOne be used with belongsToMany?

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.

Upvotes: 1

Views: 1288

Answers (2)

whoan
whoan

Reputation: 8521

@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).

Upvotes: 3

Andy Noelker
Andy Noelker

Reputation: 11269

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.

Upvotes: 3

Related Questions