Search code examples
grailsescapingassociationscriteriaconflict

Escaping association name in grails criteria to not conflict with containing class variable name


This is the simplified version of my grails domain class:

class Car {
  int year
  Model model

  List<Car> findCarsBySomeCriteria(int modelId) {
     BuildableCriteria c = createCriteria()
     List<Car> carList = (List<Car>) c.list {
        'in'("year", [1998, 1999])
        model {
            eq("id", modelId)
        }
     }

     carList
  }
}

Turns out that this criteria query fails as the model association mentioned in the query conflicts with the model property of the class.

Is there any way to escape the model in criteria query ?


Solution

  • Try createAlias, like

    List<Car> carList = (List<Car>) c.list {
        'in'("year", [1998, 1999])
        createAlias('model', 'mdl')
        eq("mdl.id", modelId)
    }