17

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?

2 Answers 2

12

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
Sign up to request clarification or add additional context in comments.

Comments

0

Try this new npm package

Sequelize-mig

Install:

npm install sequelize-mig -g / yarn global add sequelize-mig

then use it like this

sequelize-mig migration:make -n <migration name>

and it will auto generate the migration file for you with all updates

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.