2

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 ?

Community
  • 1
  • 1
kishore
  • 127
  • 1
  • 13

3 Answers3

2

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])
MKB
  • 7,587
  • 9
  • 45
  • 71
0
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

sanwrit
  • 178
  • 2
  • 12
  • Added `@Override public boolean equals(Object obj) { return obj instanceof User && (id == obj.id) }` and this method gave error **Message: could not execute query** – kishore Jun 13 '14 at 07:33
  • `Post.findAll{usersInterested.find{user}}` gave error **Message: 0** – kishore Jun 13 '14 at 07:44
0

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

kishore
  • 127
  • 1
  • 13