我在Product表中有以下列[id, name, CategoryId]和Category表,其中有[id, name]
I am having Product table with following columns [id, name, CategoryId] and Category table with [id, name]
产品型号:-
module.exports = function(sequelize, DataTypes) { var Product = sequelize.define('Product', { name: DataTypes.STRING }, { associate: function(models) { Product.belongsTo(models.Category); } }); return Product }类别模型:-
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?
更新: 续订版本sequelize 1.7.0
================================================ ================================ 答案(我如何解决此问题.):-
================================================================================ Answer(How this I have fixed.):-
我通过使用Alter命令在数据库上添加约束来完成此操作,因为通过migration的Add Foreign Key Constraint是开放的sequelize中的="noreferrer">错误.
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推荐答案
我相信您应该将onDelete放在Category模型中,而不是在product模型中.
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 }更多推荐
Sequelize.js onDelete:“级联"未删除序列化记录
发布评论