2

目前我正在做一个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再次,它没有将新属性写入原始模式,我不明白问题出在哪里,下面是我的代码,我正在尝试将两个属性“地址”和“高度”添加到用户模式中,你们可以吗?给我一些建议?谢谢!

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

1 回答 1

2

此问题已解决,您可以使用以下链接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

将新属性迁移到您的模型中。

于 2018-03-06T03:40:34.767 回答