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
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 }
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', }, }, }) },
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With