Sequelize.js: ER_ROW_IS_REFERENCED: Cannot delete or update a parent row: a foreign key constraint fails

隐身守侯 提交于 2019-12-23 15:01:46

问题


My code is:

DB.sequelize.query('SET FOREIGN_KEY_CHECKS = 0').complete(function(err) {
  if (err) {
    return done(err);
  }
  DB.sequelize.drop();
  return DB.sequelize.sync().complete(function(err) {
    if (err) {
      return done(err);
    }
  });
});

and I have some foreign key constraints, but I thought that the SET FOREIGN_KEY_CHECKS = 0 would ignore that and let me drop. Instead, the error that I get is: ER_ROW_IS_REFERENCED: Cannot delete or update a parent row: a foreign key constraint fails


回答1:


For anyone using sequelize 3.15.x they have refactored their query method so that any options after the initial SQL statement are contained in one options object. Thus the answer would look like this:

DB
    .sequelize
    .query('SET FOREIGN_KEY_CHECKS = 0', {raw: true})
    .then(function(results) {
        DB.sequelize.sync({force: true});
    });



回答2:


Try the following.

DB
    .sequelize
    .query('SET FOREIGN_KEY_CHECKS = 0', null, {raw: true})
    .success(function(results) {
        DB.sequelize.sync({force: true});
    });

The "force: true" option for sync will add "DROP TABLE IF EXISTS" to the create statements, so this should achieve what you are trying to do with the drop().

Its also worth considering this answer too: Sequelize doesn't create foreign keys as constraints.



来源:https://stackoverflow.com/questions/25891678/sequelize-js-er-row-is-referenced-cannot-delete-or-update-a-parent-row-a-fore

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!