简体   繁体   English

grails域类验证器+根据字段值设置唯一约束?

[英]grails domain class validator + set unique constraint according to field values?

Is there a way to write a custom validator that will perform different validations according to field values? 有没有办法编写一个自定义验证器,根据字段值执行不同的验证?

For example 例如

class myModel{

   A a;
   B b;
   String prop
   static belongsTo:[m:myModel]

   constraints{
       prop(validator:{
          val,obj->
                if (obj.a== null){
                  unique:[b,prop]
                }
                else{
                  unique:[a,b,prop]
                }
        })
   }
}

I'm quite confused about this. 我对此很困惑。

Thanks in advance 提前致谢

While not the most elegant solution, this should work: 虽然不是最优雅的解决方案,但这应该有效:

static constraints = {
    prop(validator: { val, obj ->
        if(obj.a == null) {
            return !myModel.findWhere(b: obj.b, prop: val)
        } else {
            return !myModel.findWhere(a: obj.a, b: obj.b, prop: val)
        }
    })
}

I don't believe there's a way to conditionally validate uniqueness based on property values without manually performing the query. 我不相信有一种方法可以根据属性值有条件地验证唯一性,而无需手动执行查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM