Search code examples
knex.js

Knex.js | running 'knex seed:run' twice gives error because of foreign key


My 'users' table has a reference to the 'business' table.

When I run knex seed:run twice I get the following error:

error: update or delete on table "businesses" violates foreign key constraint "users_business_id_foreign" on table "users"

My current seed looks like this:

exports.seed = (knex, Promise) =>
    knex('businesses').del()
        .then(() =>
            knex('businesses').insert([
                {...

What's the conventional way to solve this problem with Knex.js?


Solution

  • Depends on database, which you are using. But the conventional way in knex is exactly the same that is conventional way generally when working with SQL databases.

    Here are some ways to do it (there are probably many more valid ways to do this):

    • Delete first that table data, which is referencing your business table

    • Delete all tables in single .with statement (foreign key constraint is checked only after running the query in postgresql)

    • Delete all tables inside transaction and set checking foreign key constraints off first (mysql)

    • Truncate all tables and sequences in single TRUNCATE statement (postgresql)