Home Grails GORM - return count of objects who's array property > 0
Reply: 2

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

dre
1#
dre Published in 2018-01-08 11:54:48Z

I'm even struggling to write a title that describes my problem, so probably best to do with code;

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)

Koloritnij
2#
Koloritnij Reply to 2018-01-08 12:50:04Z

My opinion is better to add PersonCar entity.

For your question:

Car.count() > 0

As car belongTo Person, so that can't be any copy of car without been added to the person. If person is nullable you can use:

Car.countByPersonIsNotNull()

Think that if car has person, so that there will be a value in that table.

dre
3#
dre Reply to 2018-01-08 13:52:44Z

Got it! A lot simpler than I thought.

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

This effectively gives me the number of person_cars records.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.405051 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO