Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize.js onDelete: 'cascade' is not deleting records sequelize

I am having Product table with following columns [id, name, CategoryId] and Category table with [id, name]

Product Model:-

module.exports = function(sequelize, DataTypes) {   var Product = sequelize.define('Product', {     name: DataTypes.STRING   }, {     associate: function(models) {       Product.belongsTo(models.Category);     }   });   return Product } 

Category Model:-

module.exports = function(sequelize, DataTypes) {   var Category = sequelize.define('Category', {     name: { type: DataTypes.STRING, allowNull: false }   }, {     associate: function(models) {       Category.hasMany(models.Product, { onDelete: 'cascade' });     }   });   return Category } 

when I delete category, it deletes category only not the corresponding products associated with it. I don't know why this is happening?

update: Sequelize Version sequelize 1.7.0

================================================================================ Answer(How this I have fixed.):-

I accomplished this by adding constraint on database using Alter command, as Add Foreign Key Constraint through migration is an open bug in sequelize.

ALTER TABLE "Products" ADD CONSTRAINT "Products_CategoryId_fkey" FOREIGN KEY ("CategoryId") REFERENCES "Categories" (id) MATCH SIMPLE ON DELETE CASCADE 
like image 216
Sampat Badhe Avatar asked Apr 17 '14 09:04

Sampat Badhe


2 Answers

I believe you are supposed to put the onDelete in the Category model instead of in the products model.

module.exports = function(sequelize, DataTypes) {   var Category = sequelize.define('Category', {     name: { type: DataTypes.STRING, allowNull: false }   }, {     associate: function(models) {       Category.hasMany(models.Product, { onDelete: 'cascade' });     }   });   return Category } 
like image 142
agchou Avatar answered Sep 22 '22 11:09

agchou


I'm on Sequelize 4.38.0.

I had to put onDelete: 'CASCADE' not only on the association definition, but as well in the migration file.

// in models/user.js User.associate = models => {   User.belongsTo(models.Organization, {     foreignKey: { name: 'organizationId', allowNull: true },     onDelete: 'CASCADE',   }) }  // in migrations/create-users.js up: (queryInterface, Sequelize) => {   return queryInterface.createTable('Users', {     // other fields...     organizationId: {       type: Sequelize.INTEGER,       allowNull: true,       onDelete: 'CASCADE',       references: {         model: 'Organizations',         key: 'id',         as: 'organizationId',       },     },   }) }, 
like image 29
Fellow Stranger Avatar answered Sep 22 '22 11:09

Fellow Stranger