0
votes

while reading sequelize doc association part, explanation below really confuses me

hasOne and belongsTo insert the association key in different models from each other. hasOne inserts the association key in target model whereas belongsTo inserts the association key in the source model.

and also,

Player.belongsTo(Team); // Will add a teamId attribute to Player to hold the primary key value for Team

it seems that if I set relation between two models, sequelize automatically adds foreign key to the target model.

but according to the article, https://lorenstewart.me/2016/09/12/sequelize-table-associations-joins/z

we have to manually add foreign key to the model file.

which one is right..?

it has been a while since I questioned about this issue.

Any detailed explanation would really be appreciated.

Any recommended articles about sequelize association to read would also be appreciated since sequelize doc seems not that kind for ORM beginners.

1
@ArifKhan thanks for your comment, but that is totally different question from what I am asking. I am questioning about whether that relation statement adds foreign key automatically or not. this is the issue about whether we have to manually add foreign key to the target model or not. - jwkoo

1 Answers

2
votes

Actually it depends on how are you creating your tables. Via sync or via migrations.

For example

const User = sequelize.define('user', {
  username: Sequelize.STRING,
});

const Address = sequelize.define('add', {
  address: Sequelize.STRING,
});

User.hasOne(Address);

sequelize.sync({ force: true })
  .then(() => User.create({
    username: 'test'
  }))
  .then(item => {
    console.log(item.dataValues.itemPrice);
  });

This will create a userId field in the database

database screenshot

Note that I am use sync. However if you are using migrations, you would have to create this on your own.

PS: Its better to use migrations instead of sync.