如何在迁移后向架构添加新属性?

问题描述 投票:1回答:1

目前我正在开发一个node.js项目,我在构建模式时发现了一个问题,通常,我使用http://docs.sequelizejs.com/manual/tutorial/migrations.html提供的命令行来定义我的模式,这是$ node_modules/.bin/sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string,在$ node_modules/.bin/sequelize db:migrate之后,我可以写这些属性到数据库。但是,我想知道如何在迁移后向架构添加新属性,我搜索并发现这个https://github.com/sequelize/cli/issues/133正在讨论这个问题,但是在我尝试了解决方案并再次运行$ node_modules/.bin/sequelize db:migrate后,它没有将新属性写入原始架构,我不明白问题在哪里,下面是我的代码,我试图在用户架构中添加两个属性'address'和'height',你能给我一些建议吗?谢谢!

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    let migration = [];
    migrations.push(queryInterface.addColumn(
            'address',
            'height',
            {
                type: Sequelize.STRING,
              }
        ));

    return Promise.all(migrations);
    return queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      },
      firstName: {
        type: Sequelize.STRING,
      },
      lastName: {
        type: Sequelize.STRING,
      },
      email: {
        type: Sequelize.STRING,
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
    });
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Users');
  }
};
mysql node.js migration sequelize.js sequelize-cli
1个回答
1
投票

这个问题已经解决了,你可以用下面的链接How to Add, Delete new Columns in Sequelize CLI来解决那个问题,你也可以查看sequelize的查询部分来查看文件http://docs.sequelizejs.com/class/lib/query-interface.js~QueryInterface.html,真正的答案应该是

module.exports = {
  up: function (queryInterface, Sequelize) {
    return [
      queryInterface.addColumn(
        'users',
        'height',
        {
          type: Sequelize.STRING,
        }
      ),
      queryInterface.addColumn(
        'users',
        'address',
        {
          type: Sequelize.STRING,
        }
      )
    ];
  },

  down: function (queryInterface, Sequelize) {
    return [
      queryInterface.removeColumn('users', 'height'),
      queryInterface.removeColumn('users', 'address')
    ];
  }
};

然后你可以输入

sequelize migration:create --name add-height-and-address-to-user
sequelize db:migrate

将新属性迁移到模型中。

© www.soinside.com 2019 - 2024. All rights reserved.