Search code examples
grailsgroovygrails-orm

Grails GORM searching for list items that match another list


I have three objects:

Teacher, Child, Parent

Teacher.students is a List of Child objects

Parent.children is also a List of Child objects

I want to find all the Teachers who teach a certain Parent's children.

I tried this but it only finds teachers of one child. I need this to work if a parent has multiple children.

def teachers = Teacher.withCriteria{ 
    students { 
        inList("id", parent.children.first().id ) 
    } 
}

Solution

  • You are only grabbing the first id; you need to use all the childrens' id's, which you can get using the spread (*) operator. Also, according to the docs, the method is in, not inList for criteria, but it's possible I may be missing something about the version, etc.:

    in("id", parent.children*.id)