Sequelize.js onDelete:“级联"未删除序列化记录 [英] Sequelize.js onDelete: 'cascade' is not deleting records sequelize

查看:278
本文介绍了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命令在数据库上添加约束来完成此操作,因为通过migrationAdd 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:“级联"未删除序列化记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆