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
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');
}
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?
@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.
Most helpful comment
You're correct.