How to auto generate migrations with Sequelize CLI from Sequelize models?

前端 未结 10 1237
终归单人心
终归单人心 2020-11-29 16:52

I have a set of Sequelize models. I want to use migrations, not DB Sync.

Sequelize CLI seems to be able to do this, according to this article: \"When you use the CLI

10条回答
  •  盖世英雄少女心
    2020-11-29 17:33

    While it doesn't auto generate, one way to generate new migrations on a change to a model is: (assuming that you're using the stock sequelize-cli file structure where migrations, and models are on the same level)

    1. (Same as Manuel Bieh's suggestion, but using a require instead of an import) In your migration file (if you don't have one, you can generate one by doing "sequelize migration:create") have the following code:

      'use strict';
      var models = require("../models/index.js")
      module.exports = {
        up: function(queryInterface, Sequelize) {
          return queryInterface.createTable(models.User.tableName, 
            models.User.attributes);
        },
        down: function(queryInterface, Sequelize) {
          return queryInterface.dropTable('Users');
        }
      };
      
    2. Make a change to the User model.

    3. Delete table from database.
    4. Undo all migrations: sequelize db:migrate:undo:all
    5. Re-migrate to have changes saved in db. sequelize db:migrate

提交回复
热议问题