Remove constraints in sequelize migration

余生长醉 提交于 2019-12-05 01:41:38

As of 2017 with Sequelize 4.4.2, we can remove constraints with queryInterface API:

queryInterface.removeConstraint(tableName, constraintName)

Documentation is here.

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 has removeConstraint() method if you want to remove the constraint. So you can have use something like this:

return queryInterface.removeConstraint('users', 'users_userId_key', {})

where users is my Table Name and users_userId_key is index or constraint name which is generally of the form attributename_unique_key if you have unique constraint which you wanna remove(say).

If you want to remove the index you should use:

down: function (migration, DataTypes) {
    return migration.removeIndex('Users', 'myAttribute_unique_idx');
}

The return is used to use promise style instead of callbacks. This is recommended by sequelize.

It would also be good to handle the creation of the index on your own as descripted here: http://sequelize.readthedocs.org/en/latest/docs/migrations/#addindextablename-attributes-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!