【发布时间】:2017-08-15 00:08:00
【问题描述】:
我在两个表之间有一个关联 m:n 与这样的 sequelize:
课程
module.exports = function(sequelize, DataTypes) {
var Course = sequelize.define('Course', {
.....
},
{
associate: function(models){
Course.hasMany(models.Schedule);
Course.belongsTo(models.Period);
Course.belongsTo(models.Room);
Course.belongsTo(models.Subject);
Course.belongsTo(models.School);
Course.belongsTo(models.Person, { as: 'Teacher' });
}
}
);
return Course;
};
人物
module.exports = function(sequelize, DataTypes) {
var Person = sequelize.define('Person', {
....
},
{
associate: function(models){
Person.belongsTo(models.Role, { as: 'Role' });
Person.belongsTo(models.School, { as: 'School' });
Person.belongsTo(models.Person, { as: 'Tutor' });
}
}
);
return Person;
};
以及关联表Enrollment
module.exports = function(sequelize, DataTypes) {
var Enrollment = sequelize.define('Enrollment', {
....
},
{
associate: function(models){
Enrollment.belongsTo(models.Product, {as: 'Product'});
Enrollment.belongsTo(models.School, { as: 'School' });
models.Person.belongsToMany(models.Course, {through: {model: Enrollment},foreignKey: 'StudentEnrollId'});
models.Course.belongsToMany(models.Person, {through: {model: Enrollment},foreignKey: 'CourseEnrollId'});
}
}
);
return Enrollment;
};
我尝试关注这个“example”,但没有解释太多,而是一个简单的查询,其中包含参数。
我试图存档的是获取所有课程给定一个学生 ID(人模型)。如您所见,课程模型仅保存共同构成课程的不同表的 id。 Person 模型也与不同的模型相关联,因此我使用 foreignKey: 'StudentEnrollId' 提供自定义 id 名称,但是当我尝试在包含 model : db.Person, as: 'StundetEnroll' 中指定 id 名称时,查询显示以下错误:Person (StudentEnroll) is not associated to Course
【问题讨论】:
标签: javascript mysql node.js associations sequelize.js