我有两个模型:文件和类(class)。 Files 属于 Course 并且有一个 CourseId 字段。
在某些时候,我需要在插入它们之前使用事务来验证它们,但是,我的文件模型验证规则之一验证通知的 CourseId 是否存在(它在我不使用事务的其他情况下很有用) 并且此规则在交易期间被标记,因为交易期间没有 CouseId,正如我们所预料的那样。
models.sequelize.transaction(function (t) {
// if we want to insert a new course
if (formData.courseId == 0) {
return models.course.create({
name: formData.courseName,
fieldOfStudy: formData.fieldOfStudyId
}, {transaction: t}).then(function(course) {
return models.file.create({
name: formData.name,
universityId: formData.universityId,
status: 1,
type: formData.typeId,
createdBy: userId,
file_raw: files,
courseId: course.id // here is the problem!
}, {transaction: t});
});
// if we want to use a existing one
} else {
return models.file.create({
name: formData.name,
universityId: formData.universityId,
courseId: formData.courseId,
status: 1,
type: formData.typeId,
createdBy: userId,
file_raw: files
}, {transaction: t});
}
})
如果我可以动态禁用 CourseId 字段的验证规则,则可以解决此问题,但显然这还不可能。另一种方法是虚拟字段,但这种方法并不十分“优雅”。
有什么想法吗?
最佳答案
显然,“.create() 方法”没有记录,但有一个简单的解决方案:skip
。
正如我们所见here ,方法 .validate 有一个“跳过”选项。为了解决这个问题,我们只需要将 skip 设置为 ["courseId"]:
return models.file.create({
name: formData.name,
universityId: formData.universityId,
status: 1,
type: formData.typeId,
createdBy: userId,
file_raw: files,
courseId: course.id
}, {skip: ['courseId'], transaction: t});
关于transactions - 如何在交易期间禁用特定的验证规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37538014/