首页 > 解决方案 > SET FOREIGN_KEY_CHECKS = 0 在 Sequelize 迁移中不起作用

问题描述

这是我的功能:

up: queryInterface => {
  return queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 0')
   .then(() => queryInterface.dropTable('my_table'));
},

此查询在表中有效:

SET FOREIGN_KEY_CHECKS = 0; 
DROP TABLE IF EXISTS `my_table`;

错误是

无法删除或更新父行:外键约束失败

标签: mysqlsqlsequelize.jssequelize-cli

解决方案


如果要在 Sequelize 迁移中删除约束/外键,则需要使用以下命令:

// an example of table projects and users
await queryInterface.removeConstraint('projects', 'projects_ibfk_1'); // tableName, constraintId
await queryInterface.dropTable('users');

执行 'SET FOREIGN_KEY_CHECKS = 0' 更好。

如果您不知道约束 ID(在我的例子中是 projects_ibfk_1),请使用:

const refs = await queryInterface.getForeignKeyReferencesForTable('projects');
console.log(refs);

推荐阅读