gpt4 book ai didi

mongodb - 使用迭代动态构建条件 block

转载 作者:行者123 更新时间:2023-12-02 15:36:10 45 4
gpt4 key购买 nike

我想基于几个过滤器查询属性并动态建立条件

Domain Class
PatientAttr {
def name
def value
}

标准构建代码
    if(filters.size() != 0 ){
def criteria = PatientAttr.createCriteria()
def results = criteria.list{
for (item in filters){
def name = item.name
def filter = item.filter
and{
eq 'name', name
if(filter[0] == "lt")
lt ('value', filter[1] as Double)
else if(filter[0] == "gt")
gt ('value', filter[1] as Double)
else
between ('value', filter[0] as Double, filter[1] as Double)
}
}
}

我发现,仅对列表的最后一个“和”语句进行评估。条件构建器是否允许您动态构建条件?

上面的代码应与此等效
        def results = criteria.list{
and{
eq 'name', "Serum albumin (g/dL)"
gt 'value', 3.5 as Float
}
and{
eq 'name', "M-spike (g/dL)"
gt 'value', 2.3 as Float
}
}

最佳答案

我不知道您为什么会遇到麻烦,但是由于查询的默认联合词是and,因此根本没有理由在示例中使用and{}闭包。您上面的查询与以下内容相同:

    def results = criteria.list{
eq 'name', "Serum albumin (g/dL)"
gt 'value', 3.5 as Float
eq 'name', "M-spike (g/dL)"
gt 'value', 2.3 as Float
}

如果要将最上面的项目 or放在一起,则需要将外部块包装在 or{}闭包中:
if(filters.size() != 0 ){
def criteria = PatientAttr.createCriteria()
def results = criteria.list{
or{
for (item in filters){
def name = item.name
def filter = item.filter
and{
eq 'name', name
if(filter[0] == "lt")
lt ('value', filter[1] as Double)
else if(filter[0] == "gt")
gt ('value', filter[1] as Double)
else
between ('value', filter[0] as Double, filter[1] as Double)
}
}
}
}

这将返回一个查询,其结果如下:

name is 'Serum albumin...' and value is greater than '3.5'
OR
name is 'M-spike...' and value is greater than 2.3
OR etc



希望有帮助。

关于mongodb - 使用迭代动态构建条件 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10113776/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com