Sequelize.js onDelete:“级联"不删除记录续集

编程入门 行业动态 更新时间:2024-10-28 20:22:07
本文介绍了Sequelize.js onDelete:“级联"不删除记录续集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有 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:“级联"不删除记录续集

本文发布于:2023-10-23 08:11:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1520278.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:续集   级联   js   Sequelize   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!