Search code examples
grailsgrails-orm

grails grom create criteria with many-to-many mapping


I have two domain classes: User and Book.

class Book implements Serializable{


    String bookName
    Timestamp createdDateTime

    Blob file


    static belongsTo = [User]
    static hasMany  = [user :User]
}

I am able to add user in book using addToUser() method.

But I am stuck in create criteria while applying filter in user.

def query = Book.createCriteria();

def results = query.list () {
    eq("user",userObject) // not working since user field is a list of users.
    order("createdDateTime", "desc")
}

Please help me with the correct way of filtering.


Solution

  • You need to join the user table first in a many-to-many relation. The criteria should look like:

    Book.withCriteria {
        user {
            eq("id", userObject.id)
        }
        order("createdDateTime", "desc")
    }