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 中执行此操作的方法。有没有办法做到这一点?我不想重新发明轮子;)
谢谢!!
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)
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)
| 归档时间: |
|
| 查看次数: |
3267 次 |
| 最近记录: |