grails grom create criteria with many-to-many mapping

江枫思渺然 提交于 2020-01-06 04:41:26

问题


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.


回答1:


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")
}



回答2:


I'm not 100% sure how you're trying to model your domain but maybe you want a Book to have a single user? In which case you'd have the belongsTo relationship on Book e.g.

class Book {
    String bookName
    Timestamp createdDateTime
    Blob file
    static belongsTo = [user: User]
}

Then have the hasMany relationship on User e.g.

class User {
    String name
    static hasMany = [books: Book]
}

Then you can look Books up with criteria like:

def user = User.findByName( 'bob' )

def results = Book.createCriteria().list () {
    eq( "user", user )
    order( "createdDateTime", "desc" )
}


来源:https://stackoverflow.com/questions/43959938/grails-grom-create-criteria-with-many-to-many-mapping

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