Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating knex migration

Tags:

knex.js

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?

like image 976
Muhammad Raihan Muhaimin Avatar asked May 16 '26 23:05

Muhammad Raihan Muhaimin


2 Answers

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.

like image 171
Muhammad Raihan Muhaimin Avatar answered May 18 '26 12:05

Muhammad Raihan Muhaimin


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();
  })
]);
}
like image 22
Asmita Avatar answered May 18 '26 12:05

Asmita



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!