如何在 Sequelize CLI 中添加、删除新列 [英] How to Add, Delete new Columns in Sequelize CLI

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

问题描述

我刚刚开始使用 Sequelize 和 Sequelize CLI

I've just started using Sequelize and Sequelize CLI

由于是开发时期,经常会增加和删除列.向现有模型添加新列的最佳方法是什么?

Since it's a development time, there are a frequent addition and deletion of columns. What the best the method to add a new column to an existing model?

例如,我想将一个新列 'completed' 改为 Todo 模型.我将此列添加到 models/todo.js.下一步是什么?

For example, I want to a new column 'completed' to Todo model. I'll add this column to models/todo.js. Whats the next step?

我试过 sequelize db:migrate

不工作:没有执行迁移,数据库架构已经是最新的."

推荐答案

如果你使用的是 sequelize-cli 您需要先创建迁移.这只是一个文件,它告诉引擎如何更新数据库以及在出现问题时如何回滚更改.您应该始终将此文件提交到您的存储库

If you are using sequelize-cli you need to create the migration first. This is just a file that tells the engine how to update the database and how to roll back the changes in case something goes wrong. You should always commit this file to your repository

$ sequelize migration:create --name name_of_your_migration

迁移文件如下所示:

module.exports = {
  up: function(queryInterface, Sequelize) {
    // logic for transforming into the new state
    return queryInterface.addColumn(
      'Todo',
      'completed',
     Sequelize.BOOLEAN
    );

  },

  down: function(queryInterface, Sequelize) {
    // logic for reverting the changes
    return queryInterface.removeColumn(
      'Todo',
      'completed'
    );
  }
}

然后,运行它:

$ sequelize db:migrate

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

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