Reputation: 97
I have a seed and I use bulkDelete with query interface. It's okay but I need to truncate table. I set truncate: true options and I get an 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))
And then I enable cascade like this: cascade: true but still not working
My code:
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:
ERROR: Cannot truncate a table referenced in a foreign key constraint (
vexus_panel
.visits
, CONSTRAINTvisits_ibfk_4
FOREIGN KEY (countryId
) REFERENCESvexus_panel
.countries
(id
))
Update:
I found a solution.
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);
}
}
Upvotes: 3
Views: 4352
Reputation: 49385
Disable the constraint, for the truncation
queryInterface.removeConstraint(vexus_panel.visits,visits_ibfk_4 )
And when you are done add it again
Upvotes: 2