Reputation: 282
I am now having a hard time in building my constraints, I have 3 domain classes namely Hospital, Doctor and Patient, where Hospital and Doctor has a 1:m relationship and Doctor and Patient also has a 1:m relationship. So i was asked to create a dummy data where i have to make 2 different Hospitals with Doctors and Patients. Here's my code for the domain class Hospital.
class Hospital {
String name
String location
static transients = ['patients']
static hasMany = [doctor: Doctor, patient: Patient]
static constraints = {
name(blank:false)
location(blank:false)
doctor(nullable:false)
} }
--> and here is my code for the domain class Doctor.
class Doctor {
String name
String specialization
static hasMany = [patient: Patient]
static belongsTo = [hospital: Hospital]
static constraints = {
name(blank:false)
specialization(blank:false)
patient(nullable:true)
hospital(nullable:false)
} }
--> and for the Patient domain class
class Patient {
String name
String ailment
int age
Date dateAdmit, dateDischarge
static belongsTo = [doctor: Doctor, hospital: Hospital]
static constraints = {
name(blank:false, maxSize:100)
ailment(blank:false)
age(size:1..200)
dateAdmit(nullable:true)
dateDischarge(nullable:true)
doctor(nullable:false)
hospital(nullable:false)
}}
--> I saved 2 hospitals namely hospitalA and hospitalB with doctors and patients, my problem is i need to make sure that doctor from hospitalB can't have a patient from hospitalA or the doctor and patient must be in the same hospital. i believe i need to do it with custom validator. but i dont know how since i should compare properties from different domain calsses. please help me...
Upvotes: 2
Views: 584
Reputation: 3047
This should do the trick:
doctor(nullable:false, validator: { d, inst ->
return d.hospital == inst.hospital;
})
Upvotes: 2