Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Sequelize cli db migration after changes to the model

I am starting with sequelize and was following their video tutorial online. After running

node_modules/.bin/sequelize model:create --name User --attributes username:string

node_modules/.bin/sequelize model:create --name Task --attributes title:string

which created the migration files for create user and create task. Then I had to add the associations to each model as follow:

// user.js
classMethods: {
  associate: function(models) {
    User.hasMany(models.Task);
  }
}

// task.js
classMethods: {
  associate: function(models) {
    Task.belongsTo(models.User);
  }
}

However, the migration files for creating the tables for user and task are already created. Do i have to manually update them to add the relationships? "migration:create" command creates the migration skeleton file. Do I manually fill out the skeleton files or is there a way to automatically create the complete migration file besides model creation?

P.S i have seen the following stackoverflow question: How to auto generate migrations with Sequelize CLI from Sequelize models?

like image 273
ivan Avatar asked Jul 22 '15 15:07

ivan


People also ask

How do I create a migration file in node JS?

To create a migration, execute db-migrate create with a title. node-db-migrate will create a node module within ./migrations/ which contains the following two exports: exports. up = function (db, callback) { callback(); }; exports.


1 Answers

You can create a separate migration from an empty migration file. I did that when I needed to add a few extra columns to a table.

sequelize migration:create --name users

Then in my new migration file.

module.exports = {
  up: function (queryInterface, Sequelize) {
    queryInterface.addColumn(
      'Users',
      'url',
      Sequelize.STRING
    );
  },

  down: function (queryInterface, Sequelize) {
    queryInterface.removeColumn(
      'Users',
      'url',
      Sequelize.STRING
    );
  }
};

Then just run the migrations.

sequelize db:migrate
like image 193
Johnston Avatar answered Sep 28 '22 07:09

Johnston