Search code examples
sequelize.jsmany-to-many

Sequilize - Delete ManyToMany Associations


I'm using Sequilize to program a common Student - Course relational database in NodeJS. The 2 Models are associated through the automatically generated relational table student_course:

Course.belongsToMany(Student, {
  through: "student_course",
});

Student.belongsToMany(Course, {
  through: "student_course",
});

In order to update the courses associated to a Student I am used to delete all the entries in the association table where: {studentId: "id of the selected Student"}, and insert the new associations that the user posts.

Looking at the Documentation I can see that

When an association is defined between two models, the instances of those models gain special methods to interact with their associated counterparts source

and one of these methods listed under the paragraph "Foo.belongsToMany(Bar, { through: Baz })" is the fooInstance.removeBars() which I thought would be the perfect choice to my needs.

But student.removeCourses() generates the following SQL query:

DELETE FROM `student_course` WHERE `studentId` = 6 AND `courseId` IN (NULL)

and because of courseId IN (NULL) condition the query is not working, i.e. nothing is deleted. It works if I specify the courseId like for example student.removeCourses([1,2,3]).

But how do I delete all the entries associated to one students? Should I query all the Courses and fill an array with their id? Please let me know if I should post some example code.

Thank you!


Solution

  • If you want to remove all associated courses of one student, use student.setCourses([]) instead