首页 文章

Sequelize查找belongsToMany Association

提问于
浏览
0

我有两个表之间的关联m:n,像这样的sequelize:

Course

module.exports = function(sequelize, DataTypes) {

  var Course = sequelize.define('Course', {
     .....
    },
    {
      associate: function(models){
        Course.hasMany(models.Schedule);
        Course.belongsTo(models.Period);
        Course.belongsTo(models.Room);
        Course.belongsTo(models.Subject);
        Course.belongsTo(models.School);
        Course.belongsTo(models.Person, { as: 'Teacher' });
      }
    }
  );
 return Course;
};

Person

module.exports = function(sequelize, DataTypes) {

  var Person = sequelize.define('Person', {
    ....
    },
    {
      associate: function(models){
        Person.belongsTo(models.Role, { as: 'Role' });
        Person.belongsTo(models.School, { as: 'School' });
        Person.belongsTo(models.Person, { as: 'Tutor' });
      }
    }
  );

  return Person;
};

和关联表 Enrollment

module.exports = function(sequelize, DataTypes) {

  var Enrollment = sequelize.define('Enrollment', {
      ....
    },
    {
      associate: function(models){
        Enrollment.belongsTo(models.Product, {as: 'Product'});
        Enrollment.belongsTo(models.School, { as: 'School' });

        models.Person.belongsToMany(models.Course, {through: {model: Enrollment},foreignKey: 'StudentEnrollId'});
        models.Course.belongsToMany(models.Person, {through: {model: Enrollment},foreignKey: 'CourseEnrollId'});

      }
    }

  );
  return Enrollment;
};

我试着遵循这个“example”,但没有解释太多而不是一个包含参数through的简单查询 .

我试图存档的是获得给出学生ID(人物模型)的所有课程 . 正如您所看到的,课程模型仅保存不同表格的ID,这些表格一起形成课程 . Person模型也与不同模型相关联,因此我给出了一个自定义id名称 foreignKey: 'StudentEnrollId' 但是当我尝试在include model : db.Person, as: 'StundetEnroll' 中指定id名称时,查询显示以下错误: Person (StudentEnroll) is not associated to Course

1 回答

  • 2

    您还需要在 belongsToMany 关联中定义别名 as

    models.Person.belongsToMany(models.Course, { as: 'CourseEnrolls', through: { model: Enrollment }, foreignKey: 'StudentEnrollId'});
    models.Course.belongsToMany(models.Person, { as: 'StudentEnrolls', through: { model: Enrollment }, foreignKey: 'CourseEnrollId'});
    

    现在,您将能够与所有学生一起查询 Course ,反之亦然

    models.Course.findByPrimary(1, {
        include: [
            {
                model: models.Person,
                as: 'StudentEnrolls'
            }
        ]
    }).then(course => {
        // course.StudentEnrolls => array of Person instances (students of given course)
    });
    

    您还可以使用 get/set Associations 方法来检索或设置关联对象

    // assuming that course is an instance of Course model
    course.getStudentEnrolls().then(students => {
        // here you get all students of given course
    });
    

相关问题