简体   繁体   中英

How to query on a many to many relationship in Grails?

I have the following Domain Classes:

class PreparedToWork {

    String location        
    static hasMany = [assessors: Assessor]        
}

class Assessor {

    //Some Properties

    static belongsTo = [PreparedToWork]     
    static hasMany = [preparedToWork: PreparedToWork]
}

I would like to retrieve all of the Assessors which are prepared to work in a certain location with only the prepared to work ID. I have my join table in the actual database so I'm certain the relationship is fine however have tried various querying options and have failed miserably.

App info:

  • Grails Version: 3.1.8
  • Groovy Version: 2.4.6
  • JVM Version: 1.8.0_60

I think the following is a much more natural way to describe your domain

class Location {

    String name        
    static hasMany = [preparedToWork: Assessor]        
}

class Assessor {    
    //Some Properties

    static belongsTo = [Location]     
    static hasMany = [preparedToWork: Location]
}

Then you can retrieve all of the assessors who are prepared to work in a certain location with

Assessor.executeQuery(
    "from Assessor a join a.preparedToWork l where l.id = ?", [locationId])

I would setup my domains a little different than what you have. Here is an example.

class Location{
   String name

   static hasMany = [assessors: Assessor]

   static  mapping = {
        assessors joinTable: [name: 'preparedToWork', key:'location_id']
   }
} 

class Assessor {    
    static belongsTo = [Location]  

    static hasMany = [locations: Location]

    static  mapping = {
        assessors joinTable: [name: 'preparedToWork', key:'assessor_id']
    }
} 

Once the domains are setup like this, I expect to see 3 tables location assessor preparedToWork : composite key of location_id and assessor_id

If I need to find all the assessors for a specific location, I can use following statements.

def location = Location.where{ name == "some-location" }
def assessors = location.assessors // 

Hope this helps.

After trying many different types of queries I used a detached query. I did try solution 1 however I was also querying on many other properties and the query below allowed me to do that.

def criteria = new DetachedCriteria(Assessor)
if (preparedToWork) {
  criteria = criteria.build {
    createAlias("preparedToWork", "p")
    eq("p.id", preparedToWork)
  }
}

criteria.list()

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