David Bubeník
David Bubeník

Reputation: 503

Sequelize - Prevent destroying row when used somewhere else in association

Is there way to make Sequelize.js throw exception when I try destroy row what is used somewhere in association?

As example let's have table for Roles and table for Users. They have association N:M, so any user is able to have many Roles.

Problem is when user have few roles and row of included role is removed. User just loose this role. How to prevent role from removing unless association is removed first?

Upvotes: 2

Views: 367

Answers (1)

KenOn10
KenOn10

Reputation: 1968

You can control this in the association using the onDelete and onUpdate, like this:

User.hasMany(Roles, { foreignKey: "whatever", onDelete: 'restrict', onUpdate: 'restrict'}); 

The Foreign Key section of the manual mentions the options ...

Upvotes: 1

Related Questions