Search code examples
databasegrailshqlgrails-ormhibernate-criteria

Grails GORM - return count of objects who's array property > 0


Consider the following;

class Person {
    int id
    String name

    static hasMany = [cars : Car]
}

class Car {
   int id
   String brand

   static belongsTo = Person
   static hasMany = [owners: Person]
}

The above will result in a person_cars join table. All I'm trying to find out is if there are any entries in that table, in words;

Do any Persons currently exist who own a car.

Happy to use any mechanism available (finders/criteria/HQL etc)


Solution

  • Got it! A lot simpler than I thought.

     Person.createCriteria().count {
       owners {
         count
       }
     }
    

    This effectively gives me the number of person_cars records.