marko
marko

Reputation: 3776

Count length of hasMany property

I have a domain class:

class Person{
 static hasMany = [friends:Person]
 ....
}

What I'm looking to do is to filter out Persons based on the number of friends they have.

This is what I came up with, and it does the job:

Person.where{
 friends.size() == 3
}

It's slow as hell and I could do without the list, so ideally I'd just like to run something like:

select count(*) from Person where size(friends) == 3

I've searched like a maniac but I can't find that much information on countBy (I guess what I'm trying to do is countWhere).

Any input is appreciated.

Upvotes: 0

Views: 166

Answers (1)

doelleri
doelleri

Reputation: 19702

With a where query, you should be able to use count() instead of listing all the matches. where creates a DetachedCriteria that supports a number of operations.

Person.where { friends.size() == 3 }.count()

If that doesn't work as well as I think it should, you might need to use a Criteria with a projection to only return the count.

Person.withCriteria {
    sizeEq 'friends', 3
    projections {
        rowCount()
    }
}

Upvotes: 2

Related Questions