How to know who is the parent in a Grails hasMany relationship?
Asked Answered
E

2

5

We have an old application where the relationship is defined as below:

class Practice {
   String name
   static hasmany = [doctors:Doctor]
}

and

class Doctor {
  String name
}

There is not a belongsTo relationship defined in Doctor as we do not want to cascade the delete of a doctor when Practice is deleted. This is a very old code and do not want to change it.

Now according to the new functionality, the user should know which Practices the Doctor is linked to while viewing the details of a Doctor. Can anyone help me knowing which is the easiest way of achieving this without making changes to the domain object?

Eyra answered 20/3, 2012 at 16:9 Comment(0)
P
7

If variable doctor contains the doctor you want to list practices from, you can get a list of Practice objects having this doctor in their doctors relationship by issuing the following criteria query:

def practices = Practice.withCriteria {
  doctors {
    idEq(doctor.id)
  }
}
Portcullis answered 20/3, 2012 at 16:15 Comment(1)
Wow! That was simple. Thanks a lot for the quick response.Eyra
F
0

Just for record

def practices = Practice.withCriteria {
  doctors {
    eq("id",doctor.id)
  }
}
Farro answered 13/3, 2014 at 6:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.