Amit Sirohiya
Amit Sirohiya

Reputation: 333

Sorting domain class properties with respect to another domain class properties

I've two domain classes

1.CustomerInterest.groovy

static hasMany = [activities:Activity]
static belongsTo=[customer:Customer,projectProperty:ProjectProperty]

static mapping={
        activities sort:'dateCreated',order:'desc'
    }

2.Activity.groovy

Date dateCreated

static belongsTo = [customerInterest:CustomerInterest, employee:Employee]

In a controller i am doing this..

def customerDetails(Customer customer)
    {   

      def customerInterest=customer.customerInterests
       render view:"customerDetails",model:[customerInterest:customerInterest]
    }

customerDetails.gsp

<g:each in="${customerInterest}" var="ci">
    ${ci}
</g:each>

**

Question: I want to sort CustomerInterest on property dateCreated of Activity domain.

**

Any help as soon as possible would be appreciated.

Upvotes: 0

Views: 178

Answers (2)

MKB
MKB

Reputation: 7619

Try this

def customerInterest=customer.customerInterests.sort { it.activities.dateCreated }

Upvotes: 1

matcauthon
matcauthon

Reputation: 2261

Instead of using the sort order in the mappings definition, you can use the old java Comparable-interface:

class Foo implements Comparable {

  int compareTo(anotherObject) {
    // complex logic returning -1 or 0 or 1
  }
}

Then you can call listOfFoos.sort() and it will sort it with the help of the compareTo-method.

Beware that (equals) == will also use this method, so ensure that (only) identical objects will return 0.

Upvotes: 0

Related Questions