FindAll或在Sequelize模型上添加或设置后查找

时间:2018-06-25 14:22:18

标签: associations sequelize.js

如果我定义了几个Sequelize模型 (MySQL,没关系)

const Course = Model.DB.define('COURSE', {
    id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    name: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true
    }
});

const Student = Model.DB.define('STUDENT', {
    id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    name: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true
    }
});

const CourseStudents = Model.DB.define('COURSE_STUDENTS', {
    courseId: {
        type: DataTypes.INTEGER,
        field: 'course_id'
    },
    studentId: {
        type: DataTypes.INTEGER,
        field: 'student_id'
    }
});

Student.belongsToMany(Course, {
    as: 'courses',
    through: CourseStudents,
    foreignKey: 'studentId',
    otherKey: 'courseId'
});

Course.belongsToMany(Student, {
    as: 'students',
    through: CourseStudents,
    foreignKey: 'courseId',
    otherKey: 'studentId'
});

表已正确创建,并且似乎都井井有条。

然后,我们创建模型:

const course = await Course.create(
    {
        name: 'Algo'
    }
);

const john = await Student.create({name: 'John'});
const jane = await Student.create({name: 'Jane'});

course.addStudents([john, jane]);

可以再次正确创建数据。

但是,如果我在之后立即调用以下内容:

const courseById = await Course.find({
    where: {name: 'Algo'},
    include: [
        {
            model: Student,
            as: 'students',
            attributes: ['name']
        }
    ]
});

结果不是我期望的-它不包含任何学生。

我必须在创建模型时对我所使用的Courses模型实例进行某种同步/重新加载,以使find返回学生:

// note that this is the instance we've got above
await Course.sync();

const courseById = await Course.find({
    where: {name: 'Algo'},
    include: [
        {
            model: Student,
            as: 'students',
            attributes: ['name']
        }
    ]
});

有什么作用?

0 个答案:

没有答案