Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sequelize.js

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

like image 611
Shamoon Avatar asked Dec 08 '22 06:12

Shamoon


2 Answers

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});
    });
like image 144
trendsetter37 Avatar answered Apr 13 '23 14:04

trendsetter37


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.

like image 40
Kinetic Avatar answered Apr 13 '23 13:04

Kinetic