Search code examples
grailsgroovyorm

Find subdomain using domain instances in Grails


In grails, how do I find subdomain using domain instances

Let say I have

class Family {
    Integer id
    Parent parent
}


class Parent {
    Interger id
    static hasMany = [children: Child]
}

class Child {
    String name
}

So in controller,

Parent mom = Family.findById(1).parent

so now, how do I use mom to get a child with name == "Child" in parent?
Is it even possible?


Solution

  • I think this should work.

    Child child = mom.children.find { it.name == 'child' }
    

    But I do not recommend using this kind of queries. Grails has many ways for querying you can read about it here http://gorm.grails.org/latest/hibernate/manual/index.html#querying. I also recommend to you this guide http://guides.grails.org/querying-gorm-dynamic-finders/guide/index.html its about dynamic finders in contrast to queries that use groovy collection methods for querying.

    I hope its help full