I'm introducing myself to the Grails environment (It's awesome). I've been reaping the benefits of dynamically generated methods like the findAllBy*
range. However, I've come to a problem and I'm unsure about how to proceed. An hour spent on Google didn't yield all that much for me either.
Problem
I have a class like the following:
class Runner {
static hasMany = [owners: Owner]
}
And in my Owner controller, I wish to find all Runner
objects, that contain a given Owner
. Effectively, I'm trying to go from the many
to the one
.
Example
If I have an Owner
object, that looks something like
Owner[name="Dave"]
And I have a Runner
with something like:
Runner[owners[Owner[name="Dave"], Owner[name="James"]]]
My query should return this Runner
object, but it should not return
Runner[owners[Owner[name="Bill"], Owner[name="James"]]]
My attempts
I've attempted to use the inList
extension, but after some further research I realised that was designed for the other way around. My code at the moment is as follows:
def runners() {
log.info("Runners")
List<Runner> runners;
Owner owner;
if (params.id) {
log.info("Id = " + params.id);
owner = Owner.get(params.id);
log.info("owner = " + owner.name);
// Grab runners in list thing.
log.info("Number of results = " + runners.size());
}
[results: results, jockeyInstance: jockey]
}
Is this something you are expecting?
assuming you have
Here is a sample you can try.
maybe not the answer for the question at hand, but you could also make the runners known to the owners like this
results in
[runnerowner.Runner : 2]
After some research into
HQL
, I found a more elegant solution that didn't require me to change theDomain
classes at all. The query I used was as follows:Where
ownerInstance
is theOwner
object being used to map to theRunner
.