Debe definir el alias as
también en el belongsToMany
asociación
models.Person.belongsToMany(models.Course, { as: 'CourseEnrolls', through: { model: Enrollment }, foreignKey: 'StudentEnrollId'});
models.Course.belongsToMany(models.Person, { as: 'StudentEnrolls', through: { model: Enrollment }, foreignKey: 'CourseEnrollId'});
Ahora podrá consultar Course
con todos sus alumnos y viceversa
models.Course.findByPrimary(1, {
include: [
{
model: models.Person,
as: 'StudentEnrolls'
}
]
}).then(course => {
// course.StudentEnrolls => array of Person instances (students of given course)
});
También puede usar get/set Associations
métodos para recuperar o establecer objetos asociados
// assuming that course is an instance of Course model
course.getStudentEnrolls().then(students => {
// here you get all students of given course
});