I have 2 Models that they gave n:m relation: Teacher, Class Now I want to do a query to show student current classes which they are in charge of (not all classes in the table).
This is my Class Model:
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;
Teacher 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'});
};
What I found and tried is:
Class.findAll({
attributes: ['id', 'name'],
include: [{
model:Staff,
attributes: ['first', 'last'],
through: {
attributes: ['StaffId', 'ClassId'],
// where:{ClassId:1}
}
}]
}).then(classes => {
res.send(classes);
});
But it shows me all the classes.
Thanks in advance for the help.