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

前端 未结 10 1149
终归单人心
终归单人心 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
    0 讨论(0)
  • 2020-11-29 17:33

    If you want to create model along with migration use this command:-

    sequelize model:create --name regions --attributes name:string,status:boolean --underscored
    

    --underscored it is used to create column having underscore like:- created_at,updated_at or any other column having underscore and support user defined columns having underscore.

    0 讨论(0)
  • 2020-11-29 17:35

    If you don't want to recreate your model from scratch, you can manually generate a migration file using the following CLI command:

    sequelize migration:generate --name [name_of_your_migration]

    This will generate a blank skeleton migration file. While it doesn't copy your model structure over to the file, I do find it easier and cleaner than regenerating everything. Note: make sure to run the command from the containing directory of your migrations directory; otherwise the CLI will generate a new migration dir for you

    0 讨论(0)
  • 2020-11-29 17:37

    I created a small working "migration file generator". It creates files which are working perfectly fine using sequelize db:migrate - even with foreign keys!

    You can find it here: https://gist.github.com/manuelbieh/ae3b028286db10770c81

    I tested it in an application with 12 different models covering:

    • STRING, TEXT, ENUM, INTEGER, BOOLEAN, FLOAT as DataTypes

    • Foreign key constraints (even reciprocal (user belongsTo team, team belongsTo user as owner))

    • Indexes with name, method and unique properties

    0 讨论(0)
提交回复
热议问题