如何使用Grails GORM获得截然不同的结果

时间:2015-04-21 10:35:33

标签: grails gorm

我有两个对象之间的一对多关系。像订单和物品

class Order {
   static hasMany = [items: ItemModel]
   ...//some properties
}

class ItemModel {
   // some properties
}

  class SearchController {
   def doSearch() {
      def criteriaOrder = Order.createCriteria();
      def order =  criteriaOrder.list(params) {
         and {
            items {
               like("partNumber", itemName)
            }
            or {
               if (customerName){
                  like('bclientName', customerName)
                  like('dclientName',customerName)
               }
            }
            if (fromDate && toDate) {
               between('orderDate', fromDate,toDate)
            }
         }
      }
     }
   }

当我要搜索它时会产生重复的结果。我在list对象上使用了unique(),它给了unqiue但是分页不起作用。

1 个答案:

答案 0 :(得分:1)

distinct projection添加到您的查询中:

基于独特的解决方案:

def order =  criteriaOrder.list(params) {
     projections{ 
       distinct 'id'
       property 'bclientName'
       property 'dclientName'
       property 'orderDate'
       // add further props you need to show in the list
     }
     and {
        items {
           like("partNumber", itemName)
        }
  ....
}.collect{ 
  Order o = new Order( bclientName:it[ 1 ], dclientName:it[ 2 ], orderDate:it[ 3 ] ) 
  o.id = it[ 0 ]
  o
}

基于groupBy的解决方案:

def order =  criteriaOrder.list(params) {
     projections{ 
       groupProperty 'id'
       max 'orderDate'
     }
     and {
        items {
           like("partNumber", itemName)
        }
  ....
}