Grails findBy for hasMany Relationship

Interesting that this is not built into grails. As many people know who use grails you automatically get dynamic “findBy” methods on persisted objects. It is incredibly useful and provides easy access to attributes of a persisted class. The only problem is when you try to do the same thing on a “hasMany” relationship of that class. For example:

1
2
3
4
class Airport {
    String name
    static hasMany = [flights:Flight]
}

You can do:

1
Airport.findByName("MSP")

You cannot do:

1
Airport.findByFlights(flight)

What do you do? In my case, I decided to make it.

Here is my implementation:

1
2
3
4
5
6
7
8
9
10
class Airport {
   static Airport findByFlight(Flight flight)
   def c = Airport.createCriteria()
   def result = c.get {
      flights {
         idEq(flight.id)
      }
   }
   return result;
}