Grails 通过多个属性查找(findAllWhere)

Grails 通过多个属性查找(findAllWhere),grails,multiple-columns,findby,Grails,Multiple Columns,Findby,我有一个对象,我必须从中过滤某些属性,其中一些属性也可以是“null”。我有一个过滤器对象和一个产品对象 在Filter对象中,我有一些反映产品对象的属性,这些属性可以填写,也可以留空。这里是课程的简略视图 Product: String name, Boolean isEmpty, ...., belongsTo [Producer, Distributor]... Filter: Boolean isEmpty, ... belongsTo [Producer, Distributor]

我有一个对象,我必须从中过滤某些属性,其中一些属性也可以是“null”。我有一个过滤器对象和一个产品对象

在Filter对象中,我有一些反映产品对象的属性,这些属性可以填写,也可以留空。这里是课程的简略视图

Product: String name, Boolean isEmpty, ...., belongsTo [Producer, Distributor]...


Filter: Boolean isEmpty, ... belongsTo [Producer, Distributor]...
使用此过滤器,我可以搜索具有特定属性(空、生产者、分销商)的所有产品

我有一个导出功能,可以在其中选择过滤器,并根据产品的选择输出信息

由于所有这些属性都可以为null,但也可以包含一个值,所以我首先考虑构造一个自己的搜索查询(组合字符串等)来构造一个SQL字符串,然后使用Product.findAll(字符串查询,字符串参数)。但由于这很乏味,我现在把它改成这样:

if(filter.producer)
    prods = Product.findAllWhere(producer:filter.producer)
if(filter.distributor)
    prods =  prods.findAll {it.distributor == filter.distributor}
if(filter.isEmpty!=null) //as it could be NULL but also false/true
    prods =  prods.findAll {it.isEmpty == filter.isEmpty}

但如果我有10-15个属性需要过滤,这将是一个相当大的任务。我对Grails或Groovy不是很有经验,但我想这可以更容易地解决,对吗?

我相信您会发现Grails标准查询是完成类似任务的一种非常好的方法。见:

当表示为条件查询时,您的示例可能如下所示:

def prods = Product.createCriteria().list {
    if(filter.producer) eq("producer", filter.producer)
    if(filter.distributor)  eq("distributor", filter.distributor)
    if(filter.isEmpty != null) eq("isEmpty", filter.isEmpty)
}

啊,好办法。。我似乎走对了路,但还没有完全走对。。谢谢,我试试这个!