Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

node.js - Sequelize.js onDelete: 'cascade' is not deleting records sequelize

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...