Du skal definere aliaset as
også i belongsToMany
forening
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 vil du være i stand til at forespørge Course
med alle dets elever og omvendt
models.Course.findByPrimary(1, {
include: [
{
model: models.Person,
as: 'StudentEnrolls'
}
]
}).then(course => {
// course.StudentEnrolls => array of Person instances (students of given course)
});
Du kan også bruge get/set Associations
metoder for at hente eller indstille tilknyttede objekter
// assuming that course is an instance of Course model
course.getStudentEnrolls().then(students => {
// here you get all students of given course
});