[英]Sequelize belongsToMany association is not working
我的workbook
是
Workbook = sequelize.define('Workbook', {
isAssessment: {
type: DataTypes.BOOLEAN,
allowNull: false
},
originalId: {
type: DataTypes.STRING,
allowNull: false
}
}, {
classMethods: {
associate: function(models) {
Workbook.belongsTo(models.Student);
Workbook.belongsTo(models.Subject);
return Workbook.belongsToMany(models.Question, {
through: models.GradedWorkbook
});
}
}
});
我有另一個模型:
GradedWorkbook = sequelize.define('GradedWorkbook', {}, {
classMethods: {
associate: function(models) {
GradedWorkbook.belongsTo(models.Answer, {
as: 'AnswerA'
});
GradedWorkbook.belongsTo(models.Answer, {
as: 'AnswerB'
});
GradedWorkbook.belongsTo(models.Answer, {
as: 'AnswerC'
});
GradedWorkbook.belongsTo(models.Answer, {
as: 'AnswerD'
});
return GradedWorkbook.belongsTo(models.Answer, {
as: 'AnswerSelected'
});
}
}
});
第三種模式
Question = sequelize.define('Question', {
active: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
flagged: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
questionText: {
type: DataTypes.TEXT,
allowNull: true
},
level: {
type: DataTypes.INTEGER,
allowNull: false
},
originalId: {
type: DataTypes.STRING,
allowNull: false
}
}, {
classMethods: {
associate: function(models) {
Question.hasMany(models.Answer);
Question.belongsTo(models.Instruction);
Question.belongsTo(models.Topic);
Question.belongsTo(models.Subject);
Question.belongsTo(models.Passage);
return Question.belongsToMany(models.Workbook, {
through: models.GradedWorkbook
});
}
}
});
當我嘗試執行查詢時:
newWorkbook = {
isAssessment: icmVal.isAssessment || false,
originalId: icmSnapshot.key()
};
db.Workbook.findOrCreate({
where: newWorkbook,
include: [db.GradedWorkbook],
defaults: newWorkbook
}).spread(function(dbWorkbook) {
return console.log(dbWorkbook);
});
我收到一個錯誤: Unhandled rejection Error: GradedWorkbook is not associated to Workbook!
。 我做錯了什么?
Workbook和GradedWorkbook之間沒有直接關聯-它僅用作直通模型。 您只能使用直接關聯,例如,一起創建問題和工作簿
Workbook.findOrCreate({
include: [db.Question]
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.