Sequelize.js onDelete: 'cascade' does not delete records

I have a Product table with the 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 a category, it only removes a category that is not associated with it with the corresponding products. I do not know why this is happening?

update: Sequelize sequelize 1.7.0 version sequelize 1.7.0

==================================================== =============================== Answer (as I fixed it.): -

I accomplished this by adding a database constraint using the Alter command, since Add Foreign Key Constraint through migration is an open error in sequelize .

 ALTER TABLE "Products" ADD CONSTRAINT "Products_CategoryId_fkey" FOREIGN KEY ("CategoryId") REFERENCES "Categories" (id) MATCH SIMPLE ON DELETE CASCADE 
+8
source share
2 answers

I believe that you should put onDelete in the category model and not in the product 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 } 
+18
source share

Like "sequelize": "^ 3.5.1", it only works when you put onDelete='CASCADE' in the belongsTo , which is the Product model in your case. This contradicts the docs: http://sequelize.readthedocs.org/en/latest/api/associations/index.html?highlight=onDelete#hasmanytarget-options

Please check out this question: Sequelize onDelete does not work

+6
source share

All Articles