Defining many-to-many relationships in Sequelize
modeling many-to-many with a join table.
use belongsToMany through a join table, the through table holds the foreign keys, eager-load courses with include.
WHAT THIS TESTS Whether the candidate understands relational many-to-many modeling and can express it correctly in an ORM, including eager loading.
A GOOD ANSWER COVERS A many-to-many relationship means each student can take many courses and each course can have many students. Relationally this requires a junction (join) table that stores pairs of foreign keys, one row per enrollment. In Sequelize you express this with belongsToMany on both models, pointing at a through table: Student.belongsToMany(Course, { through: Enrollment }) and Course.belongsToMany(Student, { through: Enrollment }). The through table holds studentId and courseId, and can carry extra columns such as enrolledAt or grade, which is why defining it as a real model is useful. Sequelize then generates helper methods like student.getCourses and student.addCourse. To read one student with all their courses in a single query, use eager loading: Student.findByPk(id, { include: Course }), which joins through the junction table and returns the student with a nested courses array.
COMMON WRONG ANSWERS Using hasMany and belongsTo, which model one-to-many, not many-to-many. Forgetting the through table entirely. Querying courses with a separate round trip per student instead of eager loading, reintroducing N+1. Putting both foreign keys directly on Student or Course, which cannot represent the relationship.
LIKELY FOLLOW-UPS How do you store data on the relationship itself, like a grade? How do you avoid N+1 here? How do you add or remove an enrollment? What indexes belong on the join table?
ONE CONCRETE EXAMPLE Define Enrollment as the through model with studentId, courseId, and grade. Then const student = await Student.findByPk(42, { include: Course }) returns the student plus student.Courses, the full list of enrolled courses, resolved in one joined query. Adding an enrollment is await student.addCourse(course, { through: { grade: 'A' } }).
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.