Reputation: 1
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^^
Upvotes: 0
Views: 927
Reputation: 75671
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"
}
Upvotes: 1