如何在交易期间禁用特定的验证规则?

dyg*_*ufa 3 transactions sequelize.js

我有两个模型:文件和课程。文件属于 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});
    }
})
Run Code Online (Sandbox Code Playgroud)

如果我可以动态禁用 CourseId 字段的验证规则,这可以解决,但显然这还不可能。另一种方法是虚拟字段,但这种方法不是很“优雅”。

有任何想法吗?

dyg*_*ufa 5

显然,这是不是证明了“.create()方法”,但有一个简单的解决方案:skip

正如我们在这里看到的,方法 .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});
Run Code Online (Sandbox Code Playgroud)