如何在Sequelize现有模型中添加列? [英] How to add column in Sequelize existing model?

查看:917
本文介绍了如何在Sequelize现有模型中添加列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已使用此命令添加了模型和迁移文件

I have added a model and a migration file using this command

node_modules/.bin/sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string

现在,我想在现有表(模型)中添加一些字段,如性别和年龄.我手动更改了模型并触发了此命令

Now I wanted to add few more fields like gender and age in to the existing table(model). I changed model manually and fire this command

node_modules/.bin/sequelize db:migrate

但是,它的回应是未执行任何迁移,数据库架构已经是最新的. "

But it is responding that "No migrations were executed, database schema was already up to date. "

User.js

'use strict';
module.exports = (sequelize, DataTypes) => {
  var User = sequelize.define('User', {
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    email: DataTypes.STRING
  }, {});
  User.associate = function(models) {
    // associations can be defined here
  };
  return User;
};

预先感谢您:)

推荐答案

Suvethan的回答是正确的,但是迁移代码片段中有一个小错误. Sequelize迁移期望返回一个承诺,这在生成的迁移框架的注释中指出:

Suvethan's answer is correct, but the migration code snippet has a minor bug. Sequelize migrations expect a promise to be returned, which is noted in a comment in the generated migration skeleton:

Add altering commands here.
Return a promise to correctly handle asynchronicity.

Example:
return queryInterface.createTable('users', { id: Sequelize.INTEGER });

因此,返回一组承诺可能会导致意外结果,因为无法保证在继续下一次迁移之前,所有的承诺都将得到解决.对于大多数操作,您几乎不会遇到任何问题,因为大多数事情将在Sequelize关闭该过程之前完成.但是,我认为在进行数据库迁移时要比后悔更安全.您仍然可以利用承诺的数组.您只需要将其包装在Promise.all调用中即可.

So, returning an array of promises can potentially lead to unexpected results because there's no guarantee that all of the promises will have resolved before moving on to the next migration. For most operations you're unlikely to run into any issues since most things will complete before Sequelize closes the process. But I think it's better to be safe than sorry when it comes to database migrations. You can still leverage the array of promises; you just need to wrap it in a Promise.all call.

Suvethan的示例,但带有Promise.all:

module.exports = {
  up: function (queryInterface, Sequelize) {
    return Promise.all([
      queryInterface.addColumn(
        'Users',
        'gender',
         Sequelize.STRING
       ),
      queryInterface.addColumn(
        'Users',
        'age',
        Sequelize.STRING
      )
    ]);
  },

  down: function (queryInterface, Sequelize) {
    // logic for reverting the changes
  }
};

这篇关于如何在Sequelize现有模型中添加列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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