检查 Sequeulize PostgreSQL ORM (Node.js) 中的约束

Loe*_*sen 6 postgresql node.js sequelize.js

我正在使用 Sequelize 作为带有 PostgreSQL 引擎的 ORM。使用原始查询时,我可以创建一个表并包含带有“CHECK”约束的列,例如

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CHECK (price > 0)
);
Run Code Online (Sandbox Code Playgroud)

在文档中,我在定义模型时找不到在 Sequelize 中执行此操作的方法。有没有办法做到这一点?我不想重新发明轮子;)

谢谢!!

mcm*_*iii 5

module.exports = {

    up: (queryInterface, Sequelize) => {

        return queryInterface.createTable('Products', {
            product_no: {
                type: Sequelize.INTEGER
            },
            price: {
                type: Sequelize.NUMERIC
            },
            name: {
                type: Sequelize.TEXT
            }
        }).

        then(() => queryInterface.addConstraint('Products', ['price'], {
            type: 'check',
            where: {
                price: {
                    [Sequelize.Op.gt]: 0
                }
            }
        }));
    },

    down: (queryInterface, Sequelize) => {
        return queryInterface.dropTable('Products');
    }
};
Run Code Online (Sandbox Code Playgroud)

  • 是否可以在模型定义中声明检查约束? (2认同)

thg*_*ell -6

查看“验证”部分

var Product = sequelize.define('product', {
  price: {
    validate: {
      min: 0  // Only allow values >= 0
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

您还可以设置自定义验证规则:

var Product = sequelize.define('product', {
  price: {
    validate: {
      isPositive: function (value) {
        return value > 0;  // Don't allow 0.
      }
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 我相信这只会增强应用程序层的价值。我认为这实际上并没有对谈判桌施加限制。如果您使用的是sequelize 迁移,则可以运行原始查询来自行插入约束。 (4认同)