简体   繁体   中英

Query many-to-many with createCriteria in Grails

How do I query a many-to-many by using createCriteria? Here are my models,

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

And I have 3 tables that generated by GORM in my database,

role              role_user                  user 
---------------   -------------------------  ---------------------------------
|id  |name    |   |role_users_id |user_id |  |id |name     |email            |
---------------   -------------------------  ---------------------------------
|1   |Owner   |   |1             |1       |  |1  |Harry    |harry@mail.com   |
|2   |Designer|   |2             |2       |  |2  |Hermione |hermione@mail.com|
|3   |Cleaner |   |3             |3       |  |3  |Ron      |ron@mail.com     |
---------------   -------------------------  ---------------------------------

I want to get users who is a 'owner' and 'designer' and I have to use createCriteria because I am going to use pagination.

Using your relationships it's hard to query based on the user table but you can get what you want by the following:

List<User> users = []

Role.withCriteria { 
    or { 
       eq( "name", "Owner")
       eq( "name", "Designer") 

    }
}.each { users += it.users }

If you are willing to change your schema and add Role role to User , you can do the following:

List<User> users = User.createCriteria().list() { 
    role { 
       eq( "name", "Owner")
       eq( "name", "Designer") 
    }
}

FYI the syntax of createCriteria is the same as withCriteria .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM