node.js Sequelize.js onDelete:'cascade' 不删除记录 sequelize

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23128816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:10:18  来源:igfitidea点击:

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

node.jssequelize.js

提问by Sampat Badhe

I am having Producttable with following columns [id, name, CategoryId]and Categorytable with [id, name]

我有Product以下列的表格[id, name, CategoryId]Category表格[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

更新:续集版本 sequelize 1.7.0

================================================================================ Answer(How this I have fixed.):-

================================================== ============================== 答案(我是如何解决的。):-

I accomplished this by adding constraint on database using Altercommand, as Add Foreign Key Constraintthrough migrationis an open bugin sequelize.

我做到了这一点通过增加使用数据库约束Alter命令,如Add Foreign Key Constraint通过migration是一个开放的bugsequelize

ALTER TABLE "Products"
ADD CONSTRAINT "Products_CategoryId_fkey" FOREIGN KEY ("CategoryId")
REFERENCES "Categories" (id) MATCH SIMPLE
ON DELETE CASCADE

回答by agchou

I believe you are supposed to put the onDelete in the Category model instead of in the products model.

我相信您应该将 onDelete 放在 Category 模型中,而不是放在 products 模型中。

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
}

回答by Liwen

As of "sequelize": "^3.5.1", it only works when you put onDelete='CASCADE'in the belongsTodeclaration, which is the Productmodel in your case. This contradicts the docs: http://sequelize.readthedocs.org/en/latest/api/associations/index.html?highlight=onDelete#hasmanytarget-options

作为“sequelize”的:“^ 3.5.1”,它只有当你把工作onDelete='CASCADE'belongsTo声明,这是Product你的情况的模型。这与文档相矛盾:http: //sequelize.readthedocs.org/en/latest/api/associations/index.html?highlight =onDelete#hasmanytarget- options

Please see this question:Sequelize onDelete not working

请看这个问题:Sequelize onDelete not working

回答by Fellow Stranger

I'm on Sequelize 4.38.0.

我在续集 4.38.0。

I had to put onDelete: 'CASCADE'not only on the association definition, but as well in the migration file.

我不仅要放在onDelete: 'CASCADE'关联定义上,还要放在迁移文件中。

// in models/user.js
User.associate = models => {
  User.belongsTo(models.Organization, {
    foreignKey: { name: 'organizationId', allowNull: true },
    onDelete: 'CASCADE',
  })
}

// in migrations/create-users.js
up: (queryInterface, Sequelize) => {
  return queryInterface.createTable('Users', {
    // other fields...
    organizationId: {
      type: Sequelize.INTEGER,
      allowNull: true,
      onDelete: 'CASCADE',
      references: {
        model: 'Organizations',
        key: 'id',
        as: 'organizationId',
      },
    },
  })
},

回答by Huy Nguyen

The problem here is some time migration script generated missing CONSTRAINTfor foreign key.

这里的问题是有一段时间CONSTRAINTforeign key.

I'm still getting issue event follow official documentfor { onDelete: 'cascade', hooks: true }.

我仍然得到问题的事件遵循正式文件{ onDelete: 'cascade', hooks: true }

Here's my solution:

这是我的解决方案:

Step 1: Create migration files as usual but no foreign keyyet. Remember defined associateas you did

步骤 1:像往常一样创建迁移文件,但foreign key还没有。记得associate像你一样定义

    Product.belongsTo(models.Category);

    Category.hasMany(models.Product);

Step 2: Create migration script to add the foreign keycolumn into table:

第 2 步:创建迁移脚本以将foreign key列添加到表中:

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.addColumn(
      'Product', // name of Source model
      'categoryId', // name of the key we're adding 
      {
        type: Sequelize.INTEGER,
        references: {
          model: 'Category', // name of Target model
          key: 'id', // key in Target model that we're referencing
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
      }
    );
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.removeColumn(
      'Product', // name of Source model
      'categoryId' // key we want to remove
    );
  }
};

Hope this help!

希望这有帮助!

I found this solution by combine from:

我通过组合找到了这个解决方案:

回答by ecdeveloper

I finally figured it wasn't working for me because of paranoid. Sequelize doesn't handle cascade, and does a MySQL cascade delete instead. With that said, if you use paranoid with your tables - cascade won't happen since the records are not really deleted from the table.

由于偏执,我终于发现它对我不起作用。Sequelize 不处理cascade,而是执行 MySQL 级联删除。话虽如此,如果您对表使用偏执狂 - 级联不会发生,因为记录并未真正从表中删除。