sequelize 文档上的关联解释 [英] sequelize association explanation on docs

查看:12
本文介绍了sequelize 文档上的关联解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读sequelize doc关联部分时,下面的解释真的让我很困惑

<块引用>

hasOne 和 belongsTo 在不同的模型中插入关联键从彼此.hasOne 在目标模型中插入关联键而 belongsTo 在源模型中插入关联键.

还有,

Player.belongsTo(Team);//会为 Player 添加一个 teamId 属性来保存 Team 的主键值

如果我设置两个模型之间的关系,sequelize 会自动将外键添加到目标模型.

但根据文章,

请注意,我使用的是 sync.但是,如果您使用迁移,则必须自己创建它.

PS:最好使用 migrations 而不是 sync.

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.

解决方案

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

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.

这篇关于sequelize 文档上的关联解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆