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に変更されたことを確認できました。