问题
I have domain classes as below:
class Account {
String name
String uniqueName
static hasMany = [roles:Role]
}
class Role {
String name
static belongsTo = [account:Account]
static hasMany = [users: User]
}
class User {
String name
}
I received Account's uniqueName from params.uniqueName. And I want to find all users list that has roles that belongsTo account.
I want to use criteria() because I want to do it in pagination.
I try like below code, it's work but it can't do a pagination.
def account = Account.findByUniqueName(params.uniqueName)
def roles = account.roles
[users : roles.users.flatten().unique()]
How should I do this?
回答1:
Try this one: add to user:
static belongsTo = [role:Role]
and use this criteria:
User.createCriteria().listDistinct {
role{
account{
eq("uniqueName", params.uniqueName)
}
}
}
回答2:
You can use criteria like this.
List<Account> results =Account.createCriteria().list
{
eq('uniqueName', params.uniqueName)
maxResults(params.max as int)
firstResult(params.offset as int)
order(params.order, "asc")
}
回答3:
Try this:
Account account = Account.findByUniqueName(params.uniqueName)
Collection users = []
account.roles.each{ role ->
users += role.users
}
log.info("Users for ${params.uniqueName} account : ${users}"
来源:https://stackoverflow.com/questions/29360825/how-to-use-createcriteria-for-many-to-many-relation-in-grails