Reputation: 6115
I have a 1 to many relationship where each group has multiple positions, i.e.
Group -1----N- Position
class Group { static hasMany = [postions: Position }
If I have a specific group instance, can't I count directly how many positions it has? I.e. call some method group.positions.??
Thanks
Upvotes: 1
Views: 779
Reputation: 75681
As OverZealous said you can call group.positions.size()
but it will be very expensive for a large number of Position
s since it will load all of them into memory just to count them, and then throw them away.
If your Position
class has a back-reference to its owning Group
class, e.g. static belongsTo = [group: Group]
, then you can use this lightweight query:
def group = ...
int positionCount = Position.countByGroup(group)
If you don't have a bidirectional relationship, you can get the count via HQL:
def group = ...
int positionCount = Group.executeQuery(
'select count(pos) from Group g ' +
'inner join g.positions pos where g=:g', [g: group])[0]
Upvotes: 8