【问题标题】:how it gonna be the associations between the models with Sequelize?模型与 Sequelize 之间的关联如何?
【发布时间】:2021-04-24 15:42:23
【问题描述】:

Hi guys can someone help to make the right associations between the models with Sequelize In my project, there are three types of product and each type got different attributes and similar attributes

大家好,有人可以帮助在 Sequelize 的模型之间建立正确的关联吗? 在我的项目中,产品分为三种类型,每种类型都有不同的属性和相似的属性

【问题讨论】:

  • 你有没有尝试过?
  • 你能解释一下你的模型之间你想要什么样的关系,从图片上看,产品模型有所有音轨、歌词、艺术作品的 FK,是吗??

标签: javascript node.js model sequelize.js node-modules


【解决方案1】:

您可以在 Sequelize here 中找到关联文档

在产品模型中


Product.associate = (models) => {
    Product.hasMany(models.Lyrics, {
      foreignKey: 'LyricsID', // FK name in Product
      sourceKey: 'id' // FK name in lyrics table
    });
    // here write same for other models (track, artwork)
    
    // for User relation where product belongs to User,
    Product.belongsTo(models.User, {
      foreignKey: { name: 'UserID', allowNull: false },
      targetKey: 'UserID', // PK name from user table
      allowNull: false
    });
};

在用户模型中

User.associate = (models) => {
    User.hasMany(models.Product, {
      foreignKey: 'UserID',
      sourceKey: 'UserID'
    });
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    相关资源
    最近更新 更多