Mysql
 sql >> Database >  >> RDS >> Mysql

Sequelizza Trova Associazione appartieneToMany

Devi definire l'alias as anche in belongsToMany associazione

models.Person.belongsToMany(models.Course, { as: 'CourseEnrolls', through: { model: Enrollment }, foreignKey: 'StudentEnrollId'});
models.Course.belongsToMany(models.Person, { as: 'StudentEnrolls', through: { model: Enrollment }, foreignKey: 'CourseEnrollId'});

Ora potrai interrogare Course con tutti i suoi studenti e viceversa

models.Course.findByPrimary(1, {
    include: [
        {
            model: models.Person,
            as: 'StudentEnrolls'
        }
    ]
}).then(course => {
    // course.StudentEnrolls => array of Person instances (students of given course)
});

Puoi anche usare get/set Associations metodi per recuperare o impostare oggetti associati

// assuming that course is an instance of Course model
course.getStudentEnrolls().then(students => {
    // here you get all students of given course
});