gpt4 book ai didi

node.js - 如何在 Sequelize 中使用 bulkDelete 截断表和级联?

转载 作者:行者123 更新时间:2023-12-03 22:33:05 28 4
gpt4 key购买 nike

我有一个种子,我将 bulkDelete 与查询界面一起使用。没关系,但我需要截断表格。我设置了 truncate: true 选项,但出现错误:

Cannot truncate a table referenced in a foreign key constraint (vexus_panel.visits, CONSTRAINT visits_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,
});
},
错误:

ERROR: Cannot truncate a table referenced in a foreign key constraint (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);
}
}

最佳答案

禁用 constraint ,以进行截断

queryInterface.removeConstraint(vexus_panel.visits,visits_ibfk_4  )
完成后再次添加

关于node.js - 如何在 Sequelize 中使用 bulkDelete 截断表和级联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64959045/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com