【问题标题】:Grails Domain: How to access parent domain data?Grails 域:如何访问父域数据?
【发布时间】:2018-01-30 19:14:51
【问题描述】:

我有一个父子域结构,我想为验证器访问子域中的父域数据。例如在下面的代码示例中,child1 有一个变量“name”,出于验证目的,我需要 child2 数据。

我怎样才能实现这种情况?

我有这样的域结构:

class Parent{
    Child child1
    Child child2

    static mapping = {
        child1 lazy:false
        child2 lazy:false
    }
}

class Child{
    String name
    // some other variables

    static belongsTo = [parent:Parent]

    static constraints = {
        name(nullable:true,validator:{val, obj ->
            if(obj.parent){
                return true
            }
            return false
        })
    }
}

我试过了 this.parent.child2 但 parent 被发现为 null。

编辑:
已更改:
static belongsTo = [parent:Parent]

也在验证器中添加:
if(obj.parent){ return true } return false

它仍然返回 false。

【问题讨论】:

    标签: validation grails groovy grails-orm domain-object


    【解决方案1】:

    替换

    static belongsTo = [Parent]
    

    static belongsTo = [parent: Parent]
    

    所以孩子知道它的父母

    【讨论】:

      【解决方案2】:

      要以@bassmartin 的回答为基础,请检查documentation 以获取自定义验证器。你的验证器应该(至少)声明两个参数,第二个是对象实例:

      validator: { val, obj ->
        //obj.parent is what you're looking for
      }
      

      【讨论】:

      • obj.parent 仍然为空。有什么遗漏吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多