1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Sequelizeでテーブルのカラム名を変更する際の手順

Posted at

Sequelizeを利用していて、テーブル中のカラム名を変更した際のメモ・言語化です。

新しくmigrationファイルを作成する

local
$ npx sequelize migration:create --name Users#(モデル名)

migrationsディレクトリに以下のようなmigarationファイルが生成されます。

'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    /**
     * Add altering commands here.
     *
     await queryInterface.renameColumn( 'Users', 'name', 'brandName' ) 
     * Example:
     * await queryInterface.createTable('users', { id: Sequelize.INTEGER });
     */
  },

  down: async (queryInterface, Sequelize) => {
    /**
     * Add reverting commands here.
     *
     * Example:
     * await queryInterface.dropTable('users');
     */
  }
};

今回はカラム名変更なのでupにコードを記載します。

1220....js
'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.renameColumn( 'Users', 'name', 'brandName' );#追記
  },

  down: async (queryInterface, Sequelize) => {
    /**
     * Add reverting commands here.
     *
     * Example:
     * await queryInterface.dropTable('users');
     */
  }
};

await queryInterface.renameColumn( 'Users'(モデル),'name'(変更前),'brandName'(変更後) );

最後に db:migrateします。

local
$ npx sequelize db:migrate
Sequelize CLI [Node: 14.4.0, CLI: 6.2.0, ORM: 6.3.5]

Loaded configuration file "config/config.json".
Using environment "development".
== 20201220000000-Users: migrating =======
== 20201220000000-Users: migrated (0.024s)
MySQL
mysql> SHOW COLUMNS FROM Users;
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int          | NO   | PRI | NULL    | auto_increment |
| brandName    | varchar(255) | YES  |     | NULL    |                |
| createdAt    | datetime     | NO   |     | NULL    |                |
| updatedAt    | datetime     | NO   |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+
8 rows in set (0.01 sec)

name→brandNameに変更されたことを確認できました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?