Matthieu Alcaro
Matthieu Alcaro

Reputation: 41

Sequelize - Where do I have to put "onDelete" option

I am currently using Sequelize 6.5.1 in a nodeJS/Express API and I would like to set up some associations between models, knowing that I am currently not using the sequelize migration feature

I have 3 models : Role, Permission_group, Permission.

Here is what I've done for the first association :

Role.hasMany(this.sequelize.models.permission_groups, {
  foreignKey: "role_id",
  onDelete: "CASCADE",
});
PermissionGroup.belongsTo(this.sequelize.models.roles, {
  foreignKey: "role_id",
});

And what i can see in the postgres database :

Foreign-key constraints:
"permission_groups_role_id_fkey" FOREIGN KEY (role_id) REFERENCES roles(_id) ON UPDATE CASCADE ON DELETE CASCADE

And here is what I've done for the second association :

PermissionGroup.hasMany(this.sequelize.models.permissions, {
  foreignKey: "permission_group_id",
  onDelete: "CASCADE",
});
Permission.belongsTo(this.sequelize.models.permission_groups, {
  foreignKey: "permission_group_id",
});

As you can see both associations works the same way and are defined the same way, but here is what I get for the second association :

Foreign-key constraints:
"permissions_permission_group_id_fkey" FOREIGN KEY (permission_group_id) REFERENCES permission_groups(_id) ON UPDATE CASCADE ON DELETE SET NULL

I tried then to define the association the reverse way like this :

PermissionGroup.hasMany(this.sequelize.models.permissions, {
  foreignKey: "permission_group_id",
});
Permission.belongsTo(this.sequelize.models.permission_groups, {
  foreignKey: "permission_group_id",
  onDelete: "CASCADE",
});

And here I got the expected behavior :

Foreign-key constraints:
"permissions_permission_group_id_fkey" FOREIGN KEY (permission_group_id) REFERENCES permission_groups(_id) ON UPDATE CASCADE ON DELETE CASCADE

It's all working this way, but I can't figure out why. I would like to understand the real onDelete strategy, and implement it the same way in all my code.

Upvotes: 2

Views: 893

Answers (1)

Maïssa Nouhaud
Maïssa Nouhaud

Reputation: 26

Are you sure you didn't define your permissions model before your permission_group model ? I think the problem come from here..

Upvotes: 1

Related Questions