U moet de alias as
. definiëren ook in de belongsToMany
associatie
models.Person.belongsToMany(models.Course, { as: 'CourseEnrolls', through: { model: Enrollment }, foreignKey: 'StudentEnrollId'});
models.Course.belongsToMany(models.Person, { as: 'StudentEnrolls', through: { model: Enrollment }, foreignKey: 'CourseEnrollId'});
Nu kun je Course
. opvragen met al zijn studenten en vice versa
models.Course.findByPrimary(1, {
include: [
{
model: models.Person,
as: 'StudentEnrolls'
}
]
}).then(course => {
// course.StudentEnrolls => array of Person instances (students of given course)
});
U kunt ook get/set Associations
. gebruiken methoden om gekoppelde objecten op te halen of in te stellen
// assuming that course is an instance of Course model
course.getStudentEnrolls().then(students => {
// here you get all students of given course
});