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

前端 未结 10 1218
终归单人心
终归单人心 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:25

    You cannot create migration scripts for existing models.

    Resources:

    • Tutorial video on migrations.

    If going the classic way, you'll have to recreate the models via the CLI:

    sequelize model:create --name MyUser --attributes first_name:string,last_name:string,bio:text
    

    It will generate these files:

    models/myuser.js:

    "use strict";
    module.exports = function(sequelize, DataTypes) {
      var MyUser = sequelize.define("MyUser", {
        first_name: DataTypes.STRING,
        last_name: DataTypes.STRING,
        bio: DataTypes.TEXT
      }, {
        classMethods: {
          associate: function(models) {
            // associations can be defined here
          }
        }
      });
      return MyUser;
    };

    migrations/20150210104840-create-my-user.js:

    "use strict";
    module.exports = {
      up: function(migration, DataTypes, done) {
        migration.createTable("MyUsers", {
          id: {
            allowNull: false,
            autoIncrement: true,
            primaryKey: true,
            type: DataTypes.INTEGER
          },
          first_name: {
            type: DataTypes.STRING
          },
          last_name: {
            type: DataTypes.STRING
          },
          bio: {
            type: DataTypes.TEXT
          },
          createdAt: {
            allowNull: false,
            type: DataTypes.DATE
          },
          updatedAt: {
            allowNull: false,
            type: DataTypes.DATE
          }
        }).done(done);
      },
      down: function(migration, DataTypes, done) {
        migration.dropTable("MyUsers").done(done);
      }
    };

提交回复
热议问题