Sequelize Find belongsToMany 关联
Posted
技术标签:
【中文标题】Sequelize Find belongsToMany 关联【英文标题】:Sequelize Find belongsToMany Association 【发布时间】:2017-08-15 00:08:00 【问题描述】:我在两个表之间有一个关联 m:n 与这样的 sequelize:
课程
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;
;
以及关联表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”,但没有解释太多,而是一个简单的查询,其中包含参数。
我试图存档的是获取所有课程给定一个学生 ID(人模型)。如您所见,课程模型仅保存共同构成课程的不同表的 id。 Person 模型也与不同的模型相关联,因此我使用 foreignKey: 'StudentEnrollId'
提供自定义 id 名称,但是当我尝试在包含 model : db.Person, as: 'StundetEnroll'
中指定 id 名称时,查询显示以下错误:Person (StudentEnroll) is not associated to Course
【问题讨论】:
【参考方案1】:您还需要在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
);
【讨论】:
谢谢,这对我帮助很大。现在我只需要使用包含来获取其他数据。以上是关于Sequelize Find belongsToMany 关联的主要内容,如果未能解决你的问题,请参考以下文章
Sequelize 地理空间查询:找到距某个位置最近的“n”个点
Sequelize Eager Loading - 返回更扁平的数据对象