简体   繁体   English

模型与 Sequelize 之间的关联如何?

[英]how it gonna be the associations between the models with Sequelize?

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 模型之间建立正确的关联在我的项目中,有三种类型的产品,每种类型都有不同的属性和相似的属性

Hi guys can someone help to make the right associations between the models with Sequelize?大家好,有人可以帮助在 Sequelize 模型之间建立正确的关联吗? In my project, there are three types of product and each type got different attributes and similar attributes在我的项目中,产品分为三种类型,每种类型都有不同的属性和相似的属性

You can find documentation for association in Sequelize here你可以在这里找到 Sequelize 中的关联文档

In Product model在产品 model


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

In User model在用户 model

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM