排序检查约束其他列

时间:2018-06-27 08:01:09

标签: javascript constraints sequelize.js

我有一个带有两个日期字段(从和直到)的模型。我想对此模型添加约束,检查这些日期是否在同一天。使用Sequelize是否可以? The documentation only showcases the check constraint with constant values

1 个答案:

答案 0 :(得分:1)

您可以使用checkwhere子句来实现

"use strict";
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface
      .createTable("Users", {
        id: {
          allowNull: false,
          autoIncrement: true,
          primaryKey: true,
          type: Sequelize.INTEGER
        },
        startDate: Sequelize.DATE,
        endDate: Sequelize.DATE,
      }).then((result) => {
        return queryInterface
          .addConstraint("Users", ['endDate'], {
            type: 'check',
            where: {
              endDate: {
                [Sequelize.Op.gt]: { [Sequelize.Op.col]: 'Users.startDate' }
              }
            }
          });
      });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable("Users");
  }
};

如果我们尝试违反此约束将行插入db中,则会收到类似以下的错误

enter image description here