Is it possible to force truncate a table with foreign key constraints so that all rows in other tables effected are also removed?
I cannot see in documentation for an option to pass to knex('tableName').truncate()
method.
You cannot truncate a table that has foreign key constraints.
But if there is a foreign key constraint on the table, SQL Server will not allow a truncate, only a delete.
A SQL query builder that is flexible, portable, and fun to use! A batteries-included, multi-dialect (PostgreSQL, MySQL, CockroachDB, MSSQL, SQLite3, Oracle (including Oracle Wallet Authentication)) query builder for Node. js, featuring: transactions. connection pooling.
I haven't found a built in way to do it, so I just drop into raw mode:
knex.raw('TRUNCATE TABLE users, products CASCADE')
You can also set this up to happen automatically in your migrations:
exports.up = function(knex) {
return knex.schema.createTable('users_products', (t) => {
t.uuid('id').primary().defaultTo(knex.raw('uuid_generate_v4()'));
t.uuid('user_id').notNullable().references('id').inTable('users').onDelete('CASCADE');
t.uuid('product_id').notNullable().references('id').inTable('products').onDelete('CASCADE');
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With