Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correct way of creating tables before trying to add foreign keys using knex migration? #938

Closed
PaulOlteanu opened this issue Aug 16, 2015 · 3 comments

Comments

@PaulOlteanu
Copy link

I have a table, table1, that has a reference to table2, and table3. What's the correct way of ensuring table2, and table3 are created before creating the foreign keys? Currently I have a migration file for every table, but I'm assuming I have to chain the creation of the tables.

Thanks

@rhys-vdw
Copy link
Member

You're correct.

// migration: <timestamp>_create_things.js

module.exports.up = function(knex, Promise) {
  // Create referenced table before referencing table.
  return knex.schema
  .createTable('first', function(first) {
    first.increments('id').primary();
  })
  .createTable('second', function(second) {
    second.increments('id').primary();
    second.integer('first_id').references('id').inTable('first').notNull().onDelete('cascade');
  });
};

module.exports.down = function(knex, Promise) {
  // Reverse order here to prevent error.
  return knex.schema
  .dropTable('second')
  .dropTable('first');
}

@PaulOlteanu
Copy link
Author

Is there a way to ensure migration files are run in a certain order? For example, is it bad practice to create all my "regular" tables in one file, and then have another migration file to create any junction tables I might need?

Or should this all be done in the same file?

@sombriks
Copy link
Contributor

@LostCross think on migration files as modifications to the entire schema, not to a single table.

for instance, the very first migration file must set the entire show.

if during the app life there is a new feature and with it some changes on the database, a new migration file shall be created.

if you do like this you'll have much less problems than to split your tables across various files.

Each file have one transaction, so if you want to sync your files execution you'll need to mess with your connection pool in order to take sequence for granted. I'ts not impossible, but the effort does not pay.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants