How to use createCriteria for many-to-many relation in Grails?

天涯浪子 提交于 2019-12-12 01:53:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!