Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails: How can I search through children in a hasMany relationship?

Tags:

grails

If I have a Client domain class, and that Client hasMany Courses. How do I find the course I'm looking for? For instance:

class Client {
    String name
    static hasMany = [courses:Course]
}

class Course {
    String name
    static belongsTo = [client:Client]
}

def client = Client.get(1)

I want to "find" or "search" within that courses relationship. Maybe something like:

client.courses.find(name:'Whatever')

Is there any way to do this with Grails?

like image 365
intargc Avatar asked Mar 13 '10 06:03

intargc


2 Answers

If you're using a second level cache and have configured it for this association, you might want to iterate over the collection (this will save you a database query if the association is in cache).

Here is an example using the clever Groovy Collection API:

def course = client.courses.find { it.name == "whatever" }

Important: If you decide to take this approach make sure to configure eager / batch fetching of courses so you don't run into the n+1 problem.

like image 85
Kimble Avatar answered Nov 16 '22 07:11

Kimble


One way is with dynamic finder methods:

Courses.findAllByClientAndName(client, 'whatever')

This would get all a client's courses named 'whatever'.

Grails also has few other ways to accomplish this.

like image 29
ataylor Avatar answered Nov 16 '22 06:11

ataylor