Search code examples
javascriptmysqltruncateknex.js

Knex truncate table with foreign key constraints


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.


Solution

  • 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');
      });
    };