Should i use belongsTo or hasOne in Laravel?
This is not about where the foreign key is.
The OP brought up 2 scenarios: A hasOne
B, A belongsTo
B
For a contextual example, let A = user and B = company.
You can say "user owns(
hasOne
) a company" and conversely you can say "user worksAt(belongsTo
) a company".
In both scenarios,
user
has acompany_id
field
Please let that sink in for a moment. Thus, discussing the location of foreign key is a non starter. The most apt answer can be found here: https://laravel.io/forum/04-20-2015-belongsto-vs-hasone
although it works, it is an incorrect description of the relationship.
To answer the OP's question: No, you should not use them interchangeably.
They are usually used in pairs
- A
belongsTo
B, BhasMany
A - B
belongsTo
A, AhasMany
B - A
hasOne
B, BhasMany
A <- this will cause problems with both sides usinghasXXX
, see link.
No, the difference depends on where your foreign key is.
In your example, if A
has a b_id
column, then A
belongsTo
B
.
If B
has an a_id
column, then A
hasOne
or hasMany
B
depending on how many B
should have.
Main difference is as below:
belongsTo
and belongsToMany
- you're telling Laravel that this table holds the foreign key that connects it to the other table.
hasOne
and hasMany
- you're telling Laravel that this table does not have the foreign key.