Grails Domain: How to access parent domain data?

倖福魔咒の 提交于 2019-12-13 08:48:19

问题


I have a parent child domain structure, and I want access parent domain data in child domain for validator. For example in the code example below, child1 has a variable 'name' and for validator purpose I need child2 data.

How can I achieve this situation?

I have domain structure like this:

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
        })
    }
}

I tried this.parent.child2 but parent is found null.

EDIT:
Changed:
static belongsTo = [parent:Parent]

Also added in validator:
if(obj.parent){ return true } return false

Still it is returning false.


回答1:


Replace

static belongsTo = [Parent]

with

static belongsTo = [parent: Parent]

so the child know its parent




回答2:


To build on @bassmartin's answer, Check the documentation for custom validators. Your validator should declare (at least) two arguments, the second of which is the object instance:

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


来源:https://stackoverflow.com/questions/45818683/grails-domain-how-to-access-parent-domain-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!