Grails - Sort by two fields in a query

时光毁灭记忆、已成空白 提交于 2019-12-21 20:03:16

问题


I Have Such a domain class in my project:

class Log  {

Integer entityId
Integer tableId
Date logDt
}

I would like to select all the records by a certain tableId, and sort them by entityId and logDt desc. Sorting by one filed works fine:

Log.findAllByTableId(tableID, [sort: 'entityId', order: 'desc'])

but when I try to sort by both fields:

Log.findAllByTableId(tableID, [sort: 'entityId,logDt', order: 'desc'])

I get an error that there is no such field 'entityId,logDt' at this table.

What is the right syntax to do so?

Thanks.


回答1:


Using the dynamic finders, you just can sort by one property.

If you would like to sort by multiple properties you could use a criteria or a HQL query.

Here is an example using a criteria:

def logs = Log.createCriteria().list {
    eq('tableId', tableID)
    order('entityId', 'desc')
    order('logDt', 'desc')
}



回答2:


Try this,

Log.findAllByTableId(tableID, [sort: ['entityId': 'desc', 'logDt': 'desc']])

It works, with Grails 3.1.9 onwards.

NB: Probably, works with some previous versions too, never tried though.



来源:https://stackoverflow.com/questions/16332369/grails-sort-by-two-fields-in-a-query

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