Grails Domain: How to access parent domain data?

2019-08-27 02:59发布

问题:

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
}