Can't get “count” and “groupBy” with Grails DetachedCriteria

爱⌒轻易说出口 提交于 2020-01-02 07:47:07

问题


I have a domain class that I use for querying .

TourIndex{
     Long tourId
     String country
     String location
     int availability
     // ... more fields
}

We use a series if "dynamic" criteria builders for searching based on a series of configurations that basically results in performing:

def detachedCriteria = new DetachedCriteria(TourSearchIndex)

detachedCriteria = detachedCriteria.build { eq('country','AR') }
detachedCriteria = detachedCriteria.build { eq('location','salta') }

I want to reutilize this logic and get the available filters with their respective results in the form

[['location1', '3'], ['location2', '5']]

My wildest guess was:

detachedCriteria = detachedCriteria.build{
  projections{
    property('location')
    countDistinct('tourId')
  }
}

But this results in a very obvious error

Caused by: org.h2.jdbc.JdbcSQLException: Column "THIS_.LOCATION" must be in the GROUP BY list; SQL statement:
select this_.location as y0_, count(distinct this_.tour_id) as y1_ from tour_search_index this_ where this_.country=? [90016-173]

With createCriteria I have a way to get the count distinct, according to How to Group property in Order Clause using Grails Criteria

def criteria = TourSearchIndex.createCriteria()

def result = criteria.list {
  projections{
    groupProperty('location')
    countDistinct('id','idDistinct')
  }
  order('idDistinct','desc') 
}

But I want to use the DetachedCriteria that already uses the rest of the application, is there a workaround for this? What I think is missing is the "groupProperty" in the DetachedProjection in DetachedCriteria's inner class.

Thanks in advance.


回答1:


I am not sure but from seeing your criteria and detachedCriteria query as well the error, you can try this

detachedCriteria = detachedCriteria.build{
  projections{
    groupProperty('location')
    countDistinct('tourId')
  }
}



回答2:


For DetachedCriteria, the syntax is a bit different.

detachedCriteria = detachedCriteria.build{

}.projections{
    property('location')
    countDistinct('tourId')
}.list()


来源:https://stackoverflow.com/questions/23461220/cant-get-count-and-groupby-with-grails-detachedcriteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!