Knex Columns with Foreign Key Constraints

Is it possible to truncate a table with foreign key constraints to delete all rows in other tables?

I do not see the documentation to go to the knex('tableName').truncate() method.

+5
source share
2 answers

I did not find a built-in way to do this, so I just go into raw mode:

  knex.raw('TRUNCATE TABLE users, products CASCADE') 

You can also set this 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'); }); }; 
+4
source

Knexjs now has a truncate() method.

 knex('accounts').truncate() Outputs: truncate `accounts` 

May not work for all cases, but should be fine for basic truncation needs.

-2
source

Source: https://habr.com/ru/post/1246651/


All Articles