Tuesday, August 26, 2008

Return the collection from a many to many relationship in grails

I thought i would blog about this one so that it is recorded somewhere. It is a tricky problem but is so easily solved with groovy.

Say i have a many to many relationship between User and Account that is controlled by the class AccountAccess. This would be my domain:

class User {

static hasMany = [accountAccesses:AccountAccess]

Date dateCreated
Date lastUpdated
String name;

}

class Account {

static hasMany = [accountAccesses:AccountAccess]

Date dateCreated
Date lastUpdated
String name

}

class AccountAccess {

static belongsTo = User;

Date dateCreated
Date lastUpdated

User user;
Account account;

}


If i wanted to get all the Accounts a user has access to i can do this:

def accounts = user.accountAccesses.collect {it.account}


It uses the collect closure of groovy. I iterate through the AccountAccess objects and add the Account object referenced by each one. The end result is i get a list of the Accounts a user has access to.

Hope this helps

0 comments: