使用 createcriteria 嵌套对象查找列表 属性

find list using createcriteria nested object property

我有一个这样的域名

 Employee {
   Address address
   String name
   String title
}

和另一个域

 Address {
  String country
  String locality 
  String city
}

现在我想找到给定城市的所有员工,我试过

  def employees = Employee.where { 
      address {
       city == params.city
        }
   }

但这行不通,我该如何实现

你可以这样写

List<Employee> employees=Employee.createCriteria().list{
    'address'{
         eq('city',params.city)
     }

}

注意:当使用eq('city',city)(相同的参数名)时,将不起作用。

访问关联属性的语法因条件和 where 查询而异。

哪里查询

def employees = Employee.where { 
  address.city == params.city
}

https://grails.github.io/grails-doc/latest/guide/GORM.html#whereQueries

条件查询

def employees = Employee.withCriteria {
    address {
        eq('city', params.city)
    }
}

https://grails.github.io/grails-doc/latest/guide/GORM.html#criteria