views:

82

answers:

1

Hello,

i got this situation: - class user with hasMany Roles and belongsTo Roles - class Role with hasMans User

how can i get the roles belongs to a user, object user is given, how can i get objects in a many-to-many szanario?

findByX doesn't work, it's affect just one table, but i need a "find" or something else to find Object overall / over many tables.

can anyone help me? and excuse my no propper english^^

+1  A: 

If you have a User class that looks like this:

class User {
   String username
   static hasMany = [roles: Role]
   static belongsTo = Role
}

and a Role class that looks like this:

class Role {
   String name
   static hasMany = [users: User]
}

then your Role class has a collection of its Users - the hasMany defines that. The same goes for User and its Roles.

So if you have a user, the user's roles are just "user.roles":

def user = User.findByUsername('foo')
user.roles.each { role ->
   println "User $user.username has role $role.name"
}

and you can do the same thing for role:

def role = Role.findByName('ROLE_ADMIN')
role.users.each { user ->
   println "User $user.username has role $role.name"
}
Burt Beckwith
thanks, it's seems to work, no error.can you tell me how i can create test-data by using bootstrap, generating user and roles simple works, but how can i bootstrap there relationship?
Oliver
You use the dynamic addToXXX methods, in this case role.addToUsers(user) - see http://grails.org/doc/latest/guide/5.%20Object%20Relational%20Mapping%20(GORM).html#5.2.1.3%20Many-to-many
Burt Beckwith