有两种解决方案
1。使用模型验证并在数据库中手动添加检查约束:
模型验证:
const FollowingModel = sequelize.define("following", {
userId: {
type: Sequelize.INTEGER,
// .. other configuration like `allowNull`
},
followingId: {
type: Sequelize.INTEGER,
// .. other configuration like `allowNull`
}
}, {
validate: {
userShouldNotFollowSelf : function() {
if(this.userId === this.followingId) {
throw Error("User should not follow self") // Use any custom error class if your application has such class.
}
}
}
}
请注意,这将允许您在不维护此约束的数据库中创建条目。
这只是ORM的应用层检查,这个应用不会允许任何userId和followingId不相同的条目。
Mysql数据库层check constraint.
CREATE TABLE `following`
(
`userId` INT NOT NULL,
`followingId` INT NOT NULL,
CONSTRAINT `no_self_following` CHECK (`userId` <> `followingId`)
-- other properties and foreign key constraints.
);
它将确保不会在userId 和followingId 相同的位置插入此类条目。
2。在sequelize查询界面声明约束。
这需要使用查询接口addConstraint 声明您的模型,如下所示
sequelize.getQueryInterface().addConstraint("following", ['userId'], {
type: 'check',
name: "no_self_following"
where: {
userId: {
[Sequelize.Op.ne]: Sequelize.col("followingId")
}
}
});
在所有数据库模型都正确同步后运行。它将添加数据库级别的约束。
使用哪一个?
方法#1 更有效。它在应用程序内部进行检查,而无需进入数据库调用,使您的数据库不那么繁忙。