Sequelize查找belongsToMany Association

时间:2017-03-22 17:44:24

标签: javascript mysql node.js associations sequelize.js

我在两个表之间有一个关联m:n,如下所示:

课程

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;
};

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;
};

关联表注册

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模型也与不同模型相关联,因此我给出了foreignKey: 'StudentEnrollId'的自定义ID名称,但是当我尝试在include model : db.Person, as: 'StundetEnroll'中指定id名称时,查询显示以下错误:{{1} }

1 个答案:

答案 0 :(得分:2)

You need to define the alias as also in the belongsToMany association

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

Now you will be able to query Course with all it's students and vice-versa

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

You can also use get/set Associations methods in order to retrieve or set associated objects

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