23/08/2017
Search parent through child in aggregation(hasMany but not belongsTo) relationship
Lets for example take these two domain objects
class Corporation {
String name
static hasMany = [locations:Location]
}
class Location {
String description
String address
}
As you can see Corporation has many locations but Location does not belong to Corporation. How would you quickly get to Corporation when you have handle to Location? Named query comes to rescue- see the changed Corporation code – “findByLocation” is the named query which acts like a dynamic property of the domain object; dynamic in the sense that it would not be persisted.
class Corporation {
String name
static hasMany = [locations:Location]
static namedQueries = {
findByLocation { locationId ->
locations { eq 'id', locationId }
}
}
}
With this changed corporation code, one can easily find the Corporation which contains the given Location. See the below code illustration-
def location = Location.findByAddress("some-location")
//use of named query findByLocation
def corporation = Corporation.findByLocation(location.id).get()
For more grails related queries please visit our blog http://www.grailsbrains.com/blog/