首页 文章

续集关于文档的关联解释

提问于
浏览
0

在阅读sequelize doc association部分时,下面的解释确实让我困惑

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

并且,

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

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

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

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

哪一个是对的..?

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

真的很感激任何详细的解释 .

关于sequelize association to read的任何推荐文章也会受到赞赏,因为sequelize doc对于ORM初学者来说似乎不那么好 .

1 回答

  • 1

    实际上,这取决于你如何创建表 . 通过 sync 或通过 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字段

    database screenshot

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

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

相关问题