简体   繁体   中英

How to make many to many relation by MySQL in JavaScript?

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.

How to implement many to many association in sequelize
I think you have not associate the relation between two tables, look the link mention above it might help you to understand what I am trying to explain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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