简体   繁体   中英

How to get distinct results using Grails GORM

I have one to many relationship between two objects. Like Order and Items

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)
            }
         }
      }
     }
   }

When I am going to search it gives duplicate result. I used unique() on list object the it gives unqiue but pagination is not working.

add distinct projection to your query:

distinct-based solution:

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-based solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM