删除sequelize迁移中的约束 [英] Remove constraints in sequelize migration
问题描述
我通过独特的约束/#changecolumntablename-attributename-datatypeoroptionsrel =nofollow> migrations.changeColumn 函数。
I'm adding a unique
constraint in a migration via the migrations.changeColumn function.
添加约束可以工作,但由于您需要提供向后迁移,删除它以相同的方式不。在向后迁移时不会给出任何错误,但是再次应用向前迁移结果可能未处理的SequelizeDatabaseError:关系myAttribute_unique_idx已存在
。
Adding the constraint works, but since you need to provide a "backwards migration", removing it the same way does not. It doesn't give any errors when migrating backwards, but again applying the forward migration results in Possibly unhandled SequelizeDatabaseError: relation "myAttribute_unique_idx" already exists
.
(使用的数据库是postgres)
(The used database is postgres)
module.exports = {
up: function (migration, DataTypes, done) {
migration.changeColumn(
'Users',
'myAttribute',
{
type: DataTypes.STRING,
unique: true // ADDING constraint works
}
).done(done);
},
down: function (migration, DataTypes, done) {
migration.changeColumn(
'Users',
'myAttribute',
{
type: DataTypes.STRING,
unique: false // REMOVING does not
}
).done(done);
}
};
我也尝试使用 removeIndex
migration.removeIndex('Users', 'myAttribute_unique_idx').done(done);
但是在还原迁移时会出现以下错误:
But it gives the following error when reverting the migration:
Possibly unhandled SequelizeDatabaseError: cannot drop index "myAttribute_unique_idx" because constraint myAttribute_unique_idx on table "Users" requires it
推荐答案
不幸的是sequelize没有内置的迁移方法来删除约束。这是为什么在删除键之前,您需要进行原始查询。
Unfortunately sequelize doesn't have a builtin migration method to remove constraint. That is why before removing key you need to make a raw query.
down: function (migration, DataTypes) {
migration.sequelize.query(
'ALTER TABLE Users DROP CONSTRAINT myAttribute_unique_idx;'
);
migration.removeIndex('Users', 'myAttribute_unique_idx');
return;
}
这篇关于删除sequelize迁移中的约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!