我现在遇到问题,我有2个域类,即医生和病人,他们有1:m的关系。这是我的课程医生的代码
class Doctor {
String name
String specialization
def doctorService
static hasMany = [patients: Patient]
static belongsTo = [hospital: Hospital]
static constraints = {
name(blank:false)
specialization(blank:false)
patients(nullable:true)
hospital(nullable:false)
}
String toString(){
"Doctor ${name} "
}
}
- >这是我的课程患者的代码:
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)
hospital(nullable:false)
doctor(nullable:false, validator:{val, obj -> val.hospital == obj.hospital})
}
String toString(){
"${name} "
}
}
- >
我想使用 executeUpdate()删除没有患者的医生。我可以使用这样的动态查找器选择没有患者的医生。
_
def d = Doctor.findAll("from Doctor as d where not exists" +
"(from Patient as p where p.doctor = d)")
_
似乎该语法在 executeUpdate()中不起作用,我只是grails中的新手。请帮帮我..谢谢......
答案 0 :(得分:10)
使用此:
Doctor.executeUpdate('delete from Doctor d where d.patients is empty')
答案 1 :(得分:-1)
你也可以这样做:
def d = Doctor.findAll("from Doctor as d where not exists" + "(from Patient as p where p.doctor = d)")*.delete()
答案 2 :(得分:-2)
您是否尝试过使用Hibernate Criteria Builder?
比executeUpdate()
Doctor.withCriteria{
isEmpty patients
}.each{it.delete()}
警告:此代码未经过测试。未经测试不得在生产中使用:-D
但这就是想法