Difference between HasOne and BelongsTo in Sequelize ORM

后端 未结 3 1319
Happy的楠姐
Happy的楠姐 2020-12-23 12:45

I am developing a sails.js app with sequelize ORM. I am a little confused as to when BelongsTo and HasOne need to be used.

The documentation states that :

3条回答
  •  情深已故
    2020-12-23 13:15

    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.

提交回复
热议问题