代码之家  ›  专栏  ›  技术社区  ›  PPShein

在mysql中连接两个表时遇到SequelizeAgerLoadingError

  •  0
  • PPShein  · 技术社区  · 7 年前

    mysql .

    教师

    module.exports = function(sequelize, Sequelize) {
        const Teachers = sequelize.define('Teachers', {
            id: {
                type: Sequelize.INTEGER, 
                autoIncrement: true, 
                primaryKey: true 
            },
            email: {
                type: Sequelize.STRING, 
                validate: {
                    isEmail: true
                }
            }
        }, {
            classMethods: {
                associate: function (models) {
                    Teachers.hasMany(models.Students);
                }
            }
        });
        return Teachers;
    }
    

    学生

    module.exports = function(sequelize, Sequelize) {
        const Students = sequelize.define('Students', {
            id: {
                type: Sequelize.INTEGER, 
                autoIncrement: true, 
                primaryKey: true 
            },
            email: {
                type: Sequelize.STRING, 
                validate: {
                    isEmail: true
                }
            }
        }, {
            classMethods: {
                associate: function (models) {
                    Students.belongsTo(models.Students);
                }
            }
        });
        return Students;
    }
    

    exports.allRegisteredStudents = function (teacherId) {
        return models.Teachers.findAll({
            where: {
                id: teacherId
            },
            include: [models.Students]
        });
    };
    

    请让我知道我错过了什么补充,谢谢。

    1 回复  |  直到 7 年前
        1
  •  1
  •   narayansharma91    7 年前

    学生不应该是学生的榜样,学生应该是教师的榜样 应该是这样的:

    module.exports = function(sequelize, Sequelize) {
    const Students = sequelize.define('Students', {
        id: {
            type: Sequelize.INTEGER, 
            autoIncrement: true, 
            primaryKey: true 
        },
        email: {
            type: Sequelize.STRING, 
            validate: {
                isEmail: true
            }
        }
    }, {
        classMethods: {
            associate: function (models) {
                Students.belongsTo(models.Teachers);
            }
        }
    });
    return Students;
    

    exports.allRegisteredStudents = async function (teacherId) {
    return await models.Teachers.findAll({
        where: {
            id: teacherId
        },
        include: [{ model: models.Students }]
    });
    

    推荐文章