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
Sampat badhe
source share