Sequelize - 使用索引和约束重命名列

pir*_*max 6 migration sequelize.js

我想用 Sequelize 创建迁移,用camelCase 重命名列,以便在snake_case 中拥有一个包含列的数据库。

我使用 Sequelize 创建迁移并使用迁移。

module.exports = {
    up: function(queryInterface, Sequelize) {
        return queryInterface.renameColumn('my_some_table', 'totoId', 'toto_id');
    },

    down: function(queryInterface, Sequelize) {
        //
    }
};
Run Code Online (Sandbox Code Playgroud)

但是...我在此列 (totoId) 和 name 列上有一个唯一约束,名为my_some_table_name_totoId_uindex,并且我在此列 (totoId) 上也有一个索引。

如何强制重命名具有唯一约束和一个索引的列?

Oma*_*mar 10

您必须删除所有约束,重命名列,然后重新添加约束。totoId对它的单一约束看起来像这样:

// 1) drop constraint
queryInterface.removeConstraint('my_some_table', 'my_constraint');

// 2) rename column
queryInterface.renameColumn('my_some_table', 'totoId', 'toto_id');

// 3) add constraint back
queryInterface.addConstraint('my_some_table', ['toto_id'], {
    type: 'unique',
    name: 'my_constraint'
});
Run Code Online (Sandbox Code Playgroud)

请记住,迁移应该是原子操作。因此,您应该按该顺序创建 3 个迁移。