Marcelo Ferraz
Marcelo Ferraz

Reputation: 3

Grails Find parent by child

I look through the internet and I didnt find yet an answer for my question. Should be pretty easy:

class Parent {
  String name
  Child child
}

When I have a child object, how can I get the Parent by it? like:

def Parent = Parent.findByChild(child)

How am I able to get a Parent object by it child?

thanks

Upvotes: 0

Views: 3660

Answers (2)

Burt Beckwith
Burt Beckwith

Reputation: 75671

def parent = Parent.findByChild(child) works fine - you can use dynamic finders for scalar fields (strings, numbers, booleans, etc.) and other objects.

Doing the reverse and finding all Child instances for a given Parent is a little more involved but can be done with HQL:

def p = Parent.get(id)
def children = Parent.executeQuery(
       'select c from Child c, Parent p where p.child=c and p=:parent',
       [parent: p])

Upvotes: 0

kevin cline
kevin cline

Reputation: 2736

Where have you looked?

Are these domain classes? If so, then you can connect them via has_many and belongs_to:

class Parent {
    String name
    List children
    static has_many = [ children: Child ]
}

class Child {
   static belongs_to = [ parent: Parent ]
}

Then you can just write child.parent

Upvotes: 3

Related Questions