如何使用Sequelize CLI从Sequelize模型自动生成迁移? [英] How to auto generate migrations with Sequelize CLI from Sequelize models?

查看:51
本文介绍了如何使用Sequelize CLI从Sequelize模型自动生成迁移?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组Sequelize模型.我要使用迁移,而不是数据库同步.

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

Sequelize CLI 似乎能够做到这一点. article/express>这篇文章: 使用CLI进行模型生成时,您还将免费获得迁移脚本."

Sequelize CLI seems to be able to do this, according to this article: "When you use the CLI for the model generation, you will gain the migration scripts for free as well."

如何使用Sequelize CLI从现有的Sequelize模型自动生成迁移?

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

推荐答案

您不能为现有模型创建迁移脚本.

You cannot create migration scripts for existing models.

资源:

如果采用经典方式,则必须通过CLI重新创建模型:

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

它将生成以下文件:

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);
  }
};

这篇关于如何使用Sequelize CLI从Sequelize模型自动生成迁移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆