0

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

2 Answers 2

3

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

3
  • I have only the child, and I want to know whose its parent. So something like def Parent = Parent.findByChild(child). and the parent has only one child, and yes its both domain classes. I actually need a "select" method to get the parent by sending it a child Oct 28, 2011 at 4:47
  • Forget about it, i was mistyping the findBy. So that code I just put works Child child = .... def parent = findByChild(child) Thanks for your attention kevin Oct 28, 2011 at 4:53
  • 4
    It's more common to write these as hasMany and belongsTo
    – doelleri
    Oct 29, 2011 at 1:12
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.