我有两个模型,假设“Person”有名字、姓氏列。 第二个是“学生”,它具有其他属性。 我想验证如果创建了新学生,则“first_name”不为空。 但我想在定义模型时这样做。这可能吗?
const Student = sequelize.define("student", {
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
validate: {
isValid() {
//here I want to validate if Person.first_name is not null, and if it is I want to throw new Error.
}
}
},
}
感谢您的帮助。
如果有人仍在寻找此解决方案
const Student = sequelize.define("student", {
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
validate: {
isValid(curVal, next) {
sequelize.models.Person <--- your other table model
.findOne({ where: { col1: curVal } }) <--- add where clause as you need
.then((result) => {
if (!result) {
throw new Error('Invalid Person!');
}
return next();
})
.catch(function (err) {
return next(err);
});
}
}
},
}