有条件地继承 allownull 约束

Sequelize allownull constraint conditionally

我需要在 sequelize 中进行迁移以更改列。如何根据另一列的值对一列使用 allowNull 约束? 例如考虑我有 A 列和 B 列。在迁移中我想要如下所示:

queryInterface.changeColumn('book', ['A'], {
     allowNull: false,
     where: { B: true } 
});

但是正如我在示例中看到的,我们不能在 changeColumn 中使用 'where'。

我认为你必须像这样使用 customValidator 来解决这个问题:

queryInterface.changeColumn('book', ['A'], {
  allowNull: true,
  validate: {
    customValidator(value) {
      if (value === null && this.B) {
        throw new Error("A not be null if B === true");
      }
    }
  }
});