Is there a 'does not contains' functionality on a collection property of a domain object for createCriteria?

梦想与她 提交于 2019-12-08 00:57:45

问题


I have a problem similar to this. But I want a does not contain functionality.

Like I have a Post domain. A Post hasMany User. What I'd like to do, using createCriteria, is something like this:

def c = Post.createCriteria()
def l = c.list (max: maxVar) {
    notContains("users", thisUser)
}

I tried using ne But no luck.

def l = c.list (max: maxVar) {
    users {
        ne('id', thisUser.id)
    }
}

To be clear, how can I get list of all the Post whose users field which is a collection does not contain thisUser ?


回答1:


You can use HQL for this

List<Post> posts = Post.executeQuery("select distinct p from Post p where :myUser not member of p.users", [myUser: user, max: maxVar])



回答2:


c.list (max: maxVar) { not { 'in'("users", thisUser) }}

Will return a list without thisUser. This works for grails version 2.*. You may need to override .equals for your User class.

There are also many other ways to this such as using .find. Please see this link http://groovy.codehaus.org/JN1015-Collections




回答3:


I was not able to get a conventional solution to it, but I solved this problem using two separate queries.

First I got all the Posts whose users contain thisUser using

users { eq('id', thisUser.id) }

Then I got max number of Post whose id does not match any of the id from above.

Post.findAllByIdNotInList(usersList.id, [max:15])

where usersList is result from first query

P.S. : Please answer if anyone has a better solution. Thanks



来源:https://stackoverflow.com/questions/24180418/is-there-a-does-not-contains-functionality-on-a-collection-property-of-a-domai

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