Search code examples
grailsgrails-ormcriteria

CreateCriteria multiple items in a hasMany relationship


The following doesn't work for searching for multiple tags:

def tags = "1,2,3".split(",")

def results = Item.createCriteria().list() {
  itemTags {
    and {
      tags.each { tag ->
        like("name", tag)
      }
    }
  }
}

But it does seem to work if I change the and to an or.

EDIT: In my debugging I found the criteria to be:

(itemTags_alias1.name=1 and itemTags_alias1.name=2 and itemTags_alias1.name=3)

Which is not what I'm aiming to accomplish. I want to check to see if an Item has all three tags.


Solution

  • I dont know if you can have a criteria for this case, but you should be able to write the hql similar to below

    Item.executeQuery("select i from Item i join i.itemTags tags where tags.name in (:names) group by i having count(i) >= :count", [names:nameList, count: nameList.size()])
    

    See this question - you will get idea of how this can be done in sql and so you can convert it to hql

    Note: Above hql query is untested but would give you idea