如何从Web应用程序中过滤Groovy / Grails闭包

时间:2014-01-15 22:33:04

标签: grails

我有一个网络应用程序,可以调用grails应用程序进行数据库调用。数据库中充满了通过常规调用返回的产品。我将从db获得的示例对象如下:

class Product{
    Boolean is_blue;
    Boolean is_round;
    Boolean is_alive;
    Boolean is_active;
    String type;
    String name;
}

我想调用grails应用程序来过滤这些布尔值,但我不知道如何通过闭包来实现,这就是我的闭包当前的样子。

def productXML = 
     Product.findAll("from Product as p where p.is_active = 1 and p.type = :type 
                      ORDER BY p.${params.sort} ${params.order}", 
                      [type: type], [max: params.max, offset: params.offset])

我最困惑的是如何将这些参数传递给闭包。任何帮助将不胜感激。感谢。

3 个答案:

答案 0 :(得分:1)

这样的东西
def productXML = 
     Product.findAll("from Product as p where p.is_active is :active \
                      and p.type = :type \
                      ORDER BY p.${params.sort} ${params.order}", 
                      [type: type, active: true], 
                      [max: params.max, offset: params.offset])

OR

def productXML = Product.findAll(params){
    type == type && is_active == active
}

您正在寻找什么?有关详细信息,请参阅findAll

答案 1 :(得分:0)

  1. 始终使用替换变量
  2. 要使参数可选,请使用此技巧(使用类型作为示例):
  3. def productXML = Product.findAll(“from Product as p其中p.is_active为:active 和(p.type =:type or:type == null) ORDER BY p.:sort:order“, [type:type,active:true,sort:params.sort,order:params.order],[max:params.max,offset:params.offset])

答案 2 :(得分:0)

我最终创建了一个查询构建器,如果在查询字符串中有is_blue = 1,我会将其添加到查询中。

    if(params.is_blue){
        query +=" and p.is_blue = ${params.is_blue}"
    }