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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…