Difference between HasOne and BelongsTo in Sequelize ORM
I agree with Krzysztof Sztompka about the difference between:
Man.hasOne(RightArm);
RightArm.belongsTo(Man);
I'd like to answer Yangjun Wang's question:
So in this case, should I use either
Man.hasOne(RightArm);
orRightArm.belongsTo(Man);
? Or use them both?
It is true that the Man.hasOne(RightArm);
relation and the RightArm.belongsTo(Man);
one do the same thing - each of these relations will add the foreign key manId
to the RightArm
table.
From the perspective of the physical database layer, these methods do the same thing, and it makes no difference for our database which exact method we will use.
So, what's the difference? The main difference lays on the ORM's layer (in our case it is Sequalize ORM, but the logic below applies to Laravel's Eloquent ORM or even to Ruby's Active Record ORM).
Using the Man.hasOne(RightArm);
relation, we will be able to populate the man's RightArm
using the Man
model. If this is enough for our application, we can stop with it and do not add the RightArm.belongsTo(Man);
relation to the RightArm
model.
But what if we need to get the RightArm
's owner? We won't be able to do this using the RightArm
model without defining the RightArm.belongsTo(Man);
relation on the RightArm
model.
One more example will be the User
and the Phone
models. Defining the User.hasOne(Phone)
relation, we will be able to populate our User
's Phone
. Without defining the Phone.belongsTo(User)
relation, we won't be able to populate our Phone
's owner (e.g. our User
). If we define the Phone.belongsTo(User)
relation, we will be able to get our Phone
's owner.
So, here we have the main difference: if we want to be able to populate data from both models, we need to define the relations (hasOne
and belongsTo
) on both of them. If it is enough for us to get only, for example, User
's Phone
, but not Phone
's User
, we can define only User.hasOne(Phone)
relation on the User
model.
The logic above applies to all the ORMs that have hasOne
and belongsTo
relations.
I hope this clarifies your understanding.
This is more universal problem.
The main difference is in semantic. you have to decide what is the relationship (Some silly example):
Man has only one right arm. Right arm belongs to one man.
Saying it inversely looks a little weird:
Right arm has a man. A man belongs to right arm.
You can have man without right arm. But alone right arm is useless.
In sequelize if RightArm and Man are models, it may looks like:
Man.hasOne(RightArm); // ManId in RigthArm
RightArm.belongsTo(Man); // ManId in RigthArm
And as you notice there is also difference in db table structure:
BelongsTo will add the foreignKey on the source where hasOne will add on the target (Sequelize creates new column 'ManId' in table 'RightArm' , but doesn't create 'RightArmId' column in 'Man' table).
I don't see any more differences.