我有2个模型,他们给了n:m关系:老师,班级 现在,我想执行一个查询以显示他们负责的学生当前班级(不是表格中的所有班级)。
这是我的班级模型:
module.exports = (sequelize, DataTypes) => {
var Model = sequelize.define('Class', {
name : DataTypes.STRING,
category : {type: DataTypes.STRING, unique: true},
day : DataTypes.ENUM('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'),
hour : DataTypes.STRING,
});
Model.associate = function(models){
this.Students = this.belongsToMany(models.Student, {through: 'StudentClass'});
};
Model.associate = function(models){
this.Staffs = this.belongsToMany(models.Staff, {through: 'ClassTeacher'});
};
Model.prototype.toWeb = function (pw) {
let json = this.toJSON();
return json;
};
return Model;
教师模型:
module.exports = (sequelize, DataTypes) => {
var Model = sequelize.define('Staff', {
first : DataTypes.STRING,
last : DataTypes.STRING,
email : {type: DataTypes.STRING, allowNull: true, unique: true, validate: { isEmail: {msg: "Email invalid."} }},
phone : {type: DataTypes.STRING, allowNull: true, unique: true, validate: { len: {args: [7, 20], msg: "Phone number invalid, too short."}, isNumeric: { msg: "not a valid phone number."} }},
password : DataTypes.STRING,
role : DataTypes.ENUM('Head', 'Teacher'),
});
Model.associate = function(models){
this.Students = this.belongsToMany(models.Student, {through: 'TeacherStudent'});
};
Model.associate = function(models){
this.Classes = this.belongsToMany(models.Class, {through: 'TeacherClass'});
};
我发现并尝试过的是:
Class.findAll({
attributes: ['id', 'name'],
include: [{
model:Staff,
attributes: ['first', 'last'],
through: {
attributes: ['StaffId', 'ClassId'],
// where:{ClassId:1}
}
}]
}).then(classes => {
res.send(classes);
});
但是它显示了我所有的课程。
预先感谢您的帮助。
答案 0 :(得分:0)
How to implement many to many association in sequelize
我认为您尚未关联两个表之间的关系,请看上面的链接,它可能有助于您了解我要解释的内容。