Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs sequelize how to truncate a foreign key referenced table

[Important: this is only relevant for Sequelize Version < 3]

I have a "myTable" mysql table in which myTable.id is referenced by a foreign key on another table. I need to truncate "myTable". Normally with mysql shell I would do:

mysql> SET FOREIGN_KEY_CHECKS = 0; truncate table myTable; SET FOREIGN_KEY_CHECKS = 1;

Is there any way of doing this with sequelize?

I have tried to execute

sequelize.query('SET FOREIGN_KEY_CHECKS = 0; truncate table myTable; SET FOREIGN_KEY_CHECKS = 1;')

but I have the error:

`Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'truncate table myTable; SET FOREIGN_KEY_CHECKS = 1' at line 1`

If I execute the queries serially, I cannot truncate the table:

ERROR 1701 (42000): Cannot truncate a table referenced in a foreign key constraint
like image 246
Juanra Avatar asked Apr 08 '14 13:04

Juanra


People also ask

How do I truncate a table in Sequelize?

JSDoc. Truncate all tables defined through the sequelize models. This is done by calling Model. truncate() on each model.

Does truncate work with foreign key?

You can't truncate a table that has a foreign key constraint, that is the whole reason for having a constraint. You will need to delete and re-create the constraints so make sure you script them out before deleting them.

Does truncate ignore foreign keys?

But if there is a foreign key constraint on the table, SQL Server will not allow a truncate, only a delete.


1 Answers

I got this by looking at another question and it worked for me on v4.13.2

MyTableModel.destroy({ truncate: { cascade: true } });
like image 108
galki Avatar answered Sep 17 '22 06:09

galki