Bạn cần xác định bí danh as cũng có trong belongsToMany liên kết
models.Person.belongsToMany(models.Course, { as: 'CourseEnrolls', through: { model: Enrollment }, foreignKey: 'StudentEnrollId'});
models.Course.belongsToMany(models.Person, { as: 'StudentEnrolls', through: { model: Enrollment }, foreignKey: 'CourseEnrollId'});
Bây giờ bạn sẽ có thể truy vấn Course với tất cả là sinh viên và ngược lại
models.Course.findByPrimary(1, {
include: [
{
model: models.Person,
as: 'StudentEnrolls'
}
]
}).then(course => {
// course.StudentEnrolls => array of Person instances (students of given course)
});
Bạn cũng có thể sử dụng get/set Associations các phương thức để truy xuất hoặc đặt các đối tượng được liên kết
// assuming that course is an instance of Course model
course.getStudentEnrolls().then(students => {
// here you get all students of given course
});