在文档上对关联进行解释 [英] sequelize association explanation on docs

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

问题描述

在阅读sequelize doc关联部分时,以下说明确实使我感到困惑

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

有一个和属于将关联密钥插入到不同的模型中 彼此. hasOne将关联密钥插入目标模型 而EmiratesTo将关联密钥插入源模型中.

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.

还有

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

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

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

但是根据文章, https://lorenstewart.me/2016/09/12/sequelize-table-associations-joins/z

我们必须手动将外键添加到模型文件中.

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

哪个是对的..?

自从我对这个问题提出质疑以来已经有一段时间了.

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

任何详细的解释都将不胜感激.

Any detailed explanation would really be appreciated.

由于sequelize doc对于ORM初学者而言不是那种类型,因此任何推荐的有关sequelize关联的推荐文章也将受到赞赏.

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

推荐答案

实际上,这取决于您如何创建表.通过sync或通过migrations.

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

例如

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);
  });

这将在数据库中创建一个userId字段

This will create a userId field in the database

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

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

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

PS: Its better to use migrations instead of sync.

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

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