简体   繁体   中英

GORM grails withCriteria query

I have 3 domain: 1) user 2) profile 3) Doctor

1) doctor extends user 2) user hasOne profile

class User {
    String username
    String password
    static hasOne = [profile: Profile]
}

class Profile {
    String fullName
    String address
    String cellno
}

class Doctor {
    String workLocation
    String specialization
}

How do I write a GORM query to list all the doctor based on specialization and workLocation with their names profile.fullName ?

Since Doctor extends User , I'm assuming the Doctor domain class looks like this:

class Doctor extends User {
    String workLocation
    String specialization
}

You can get a list of Doctor instances with a GORM query like this:

def location = 'someWorkLocation'
def spec = 'someSpecialization'

def doctors = Doctor.withCriteria {
    eq 'specialization', spec
    eq 'workLocation', location
}.list()

The query above uses the eq() method to specify the WHERE criteria. If you want the full names rather that Doctor instances you'll need a projection:

def names = doctors.withCriteria {
    eq 'specialization', spec
    eq 'workLocation', location

    projections {
        profile {
            property 'fullName'
        }
    }
}

The projection is essentially the SELECT part of the query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM