【问题标题】:How can I truncate table and cascade with bulkDelete in Sequelize?如何在 Sequelize 中截断表并使用 bulkDelete 级联?
【发布时间】:2020-11-22 20:13:21
【问题描述】:

我有一个种子,我使用带有查询接口的 bulkDelete。没关系,但我需要截断表格。我设置了 truncate: true 选项,但出现错误:

无法截断外键约束中引用的表(vexus_panel.visits、CONSTRAINTvisits_ibfk_4 FOREIGN KEY (countryId) REFERENCES vexus_panel.countries (id))

然后我像这样启用级联:级联:真实但仍然无法正常工作

我的代码:

  down: async (queryInterface, Sequelize) => {
    /**
     * Add commands to revert seed here.
     *
     * Example:
     * await queryInterface.bulkDelete('People', null, {});
     */
    await queryInterface.bulkDelete("Countries", null, {
      truncate: true,
      cascade: true,
    });
  },

错误:

错误:无法截断外键约束中引用的表(vexus_panel.visits,CONSTRAINT visits_ibfk_4 FOREIGN KEY (countryId) REFERENCES vexus_panel.countries (id))

文档:https://sequelize.org/master/class/lib/dialects/abstract/query-interface.js~QueryInterface.html#instance-method-bulkDelete

更新:

我找到了解决办法。

  down: async (queryInterface, Sequelize) => {
    const { sequelize } = queryInterface;
    try {
      await sequelize.transaction(async (transaction) => {
        const options = { transaction };
        await sequelize.query("SET FOREIGN_KEY_CHECKS = 0", options);
        await sequelize.query("TRUNCATE TABLE Countries", options);
        await sequelize.query("SET FOREIGN_KEY_CHECKS = 1", options);
      });
    } catch (error) {
      console.log(error);
    }
  }

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    禁用constraint,用于截断

    queryInterface.removeConstraint(vexus_panel.visits,visits_ibfk_4  )
    

    当你完成后再次添加它

    【讨论】:

    • 如果我这样做,我需要再次添加约束。我需要更简单的方法。我使用 Sequelize v6.3.5
    • 在 sequlize 中没有更简单的方法,在 mysql 中,您还可以禁用所有约束,然后再次启用它们,但是由于您需要 sequlize 解决方案,这就是方法。除了你编写一个程序并在每次截断时运行它,它应该变得多么容易
    • 我找到了解决方案。你能检查一下编辑过的问题吗?
    • 这和我的解决方案一样,但是你禁用了我的所有约束,这并不容易
    猜你喜欢
    • 2020-03-10
    • 2018-06-06
    • 2014-05-21
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    相关资源
    最近更新 更多