Consider two models A
and B
A
-> relatedTo B
is a one to one
relationship
What is the difference in using (A ->hasOne
-- B) and (A ->belongsTo
-- B)?
Can I use them interchangeably?
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
belongsTo
B, B hasMany
AbelongsTo
A, A hasMany
BhasOne
B, B hasMany
A <- this will cause problems with both sides using hasXXX
, see link.The model who's table contains the foreign key will have belongsTo() in it while the model who's table contains that primary key to which that foreign key is referencing to will have hasOne()... its easy the model that has the foreign key will have belongsTo() and the one that doesn't contain the foreign Key in that relationship will have hasOne(). and no they are not interchangeable using the wrong method will always return null as a result.