I find out there is two way we can write knex migration in the migration file.
exports.up = function (knex) {
return knex.schema
.createTableIfNotExists('foo', function (table) {
table.increments('id').unique();
table.string('foo1');
table.string('foo2');
})
.createTableIfNotExists('bar', function (table) {
table.increments('bar1');
table.string('bar2').index();
});
Or
exports.up = function (knex) {
return Promise.all([
knex.schema.createTableIfNotExists('foo', function (table) {
table.increments('id').unique();
table.string('foo1');
table.string('foo2');
}),
knex.schema.createTableIfNotExists('bar', function (table) {
table.increments('bar1');
table.string('bar2').index();
})
]);
}
Which one is the right way of doing it?
Answered by Ricardo Graca at Knex's github issue page
In that case it doesn't make a difference.
You would only use the Promise based one if you require some change in a table before doing another change in another table. For example, if you needed to reference a certain table from another table and none of those tables exist yet, you would create the first table (the one that doesn't depend on anything) in a promise and then when that promise resolved you would create the second table. That way you ensure that dependencies are met.
This is the right way to add knex script, as Promises are the preferred way of dealing with queries in knex, as they allow you to return values from a fulfillment handler.
exports.up = function (knex) {
return Promise.all([
knex.schema.createTableIfNotExists('foo', function (table) {
table.increments('id').unique();
table.string('foo1');
table.string('foo2');
}),
knex.schema.createTableIfNotExists('bar', function (table) {
table.increments('bar1');
table.string('bar2').index();
})
]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With