数据库迁移工具-修改表

如何修改表

  • 使用 Sequelize-Cli 管理数据库的目的就是为了监控数据库的变化
  • 所以我们不能直接修改表的结构, 如果要修改, 必须通过 migration 文件修改
  • 这样我们就能记录修改的每一步操作, 就能追踪修改的整个过程, 就能回退到指定版本

修改表步骤

  • 通过 migration:generate 创建迁移文件

image-20220201160433065

npx sequelize migration:generate --name cheng-user

image-20220201160501488

  • 在迁移文件中的 up 内部编写修改表结构的内容

进入 sequelize 官网:https://sequelize.org/v5/class/lib/query-interface.js~QueryInterface.html 相关所编写的内容都是基于官方文档当中的内容进行编写的:

image-20220201160651922

例如博主现在想要添加一列,该如何进行添加呢,博主在进行查阅官方文档的时候发现有一个方法是叫 addColumn 所以很明确的就可以知道,这是一个添加一列的相关方法,相关参数我相信也不需要我过多的进行一一解释了直接上代码如下:

'use strict';

module.exports = {
    up: (queryInterface, Sequelize) => {
        /*
          Add altering commands here.
          Return a promise to correctly handle asynchronicity.
    
          Example:
          return queryInterface.createTable('users', { id: Sequelize.INTEGER });
        */
        return queryInterface.addColumn('Users', 'age', Sequelize.INTEGER);
    },
    down: (queryInterface, Sequelize) => {
        /*
          Add reverting commands here.
          Return a promise to correctly handle asynchronicity.
    
          Example:
          return queryInterface.dropTable('users');
        */
    }
};

image-20220201173904675

  • 通过 db:migrate 执行编写好的迁移文件
npx sequelize db:migrate

image-20220201173237634

数据库当中的体现如下:

image-20220201174113883

如上可以看到我们已经成功的添加了一列 age 那么如果我需要删除这一列该如何进行删除呢,通过观察官方文档可以发现,有一个 removeColumn 但是要写在 down 内部:

'use strict';

module.exports = {
    up: (queryInterface, Sequelize) => {
        /*
          Add altering commands here.
          Return a promise to correctly handle asynchronicity.

          Example:
          return queryInterface.createTable('users', { id: Sequelize.INTEGER });
        */
        return queryInterface.addColumn('Users', 'age', Sequelize.INTEGER);
    },
    down: (queryInterface, Sequelize) => {
        /*
          Add reverting commands here.
          Return a promise to correctly handle asynchronicity.

          Example:
          return queryInterface.dropTable('users');
        */
        return queryInterface.removeColumn('Users', 'age');
    }
};

image-20220201173848363

然后在通过 db:migrate:undo 进行回退(删除)操作即可:

npx sequelize db:migrate:undo

image-20220201174336291

数据库当中的体现如下:

image-20220201174418051

posted @ 2022-02-01 17:48  BNTang  阅读(257)  评论(0)    收藏  举报