我有 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 中的github/sequelize/sequelize/issues/966"rel="noreferrer">bug.
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 模型而不是 products 模型中.
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:“级联"不删除记录续集
发布评论