Grails - sort by domain relationship attribute (using createCriteria ())

I have two domain classes with a 1: n ratio:

import Action class Task { Action actionParent String taskName } 

and

 class Action { String actionName } 

I have a list of tasks where I have an โ€œAction Nameโ€ column, I would like to sort this column by Action.actionName. Now I use the createCriteria () method [I need to use it because I have more logic to filter and sort ...], but I can only sort by "Action.id". This method is as follows:

 def criteria = Task.createCriteria(); taskList = criteria.list { if(parameters.max != null) maxResults(parameters.max) if(parameters.offset != null) firstResult(new Integer(parameters.offset)) if(parameters.sort != null && parameters.order) order(parameters.sort, parameters.order) } 

Is there a way to sort domain class data by relationship attributes?

Thanks for any replay,

Mateo

+1
source share
4 answers

if you want to adhere to the criteria approach, try something like this. Create an alias for the Action object and then access the property to sort it

  def criteria = Task.createCriteria() def taskList = criteria.list { createAlias("actionParent","_action") order( "_action.actionName") } 
+4
source

I know this is an old question, but in my specific situation (wanting to sort by association association field) it only worked when I passed the sort column directly to the list method:

 def criteria = Task.createCriteria(); taskList = criteria.list(max: parameters.max, offset: parameters.offset, sort: parameters.sort, order: parameters.order) { // Other code here... } 

When I tried to put the order information in the closure itself, Hibernate blocked the exception with the message org.hibernate.QueryException: could not resolve property: [Grails domain relation relation field] of: [Grails domain] .

+2
source

try it

  def tasksList = Task.findAll() tasksListSorted = tasksList.sort { it.actionParent.actionName } 

you can also do it

  tasksList.sort{ task1, task2 -> task1.actionParent.actionName.compareToIgnoreCase(task2.actionParent.actionName) } 
+2
source

You tried to use the listOrderBy * GORM command, so that would be something like

 def tasksList = Task.listOrderByActionName() 
+1
source

Source: https://habr.com/ru/post/970531/


All Articles