Search code examples
grailsgrails-domain-classgrails-controller

Grails Domain transients and calculations


I have a grails domain that looks like the following

User {
  sortedSet notifications
  static hasMany=[notifications:Notification]
}

Notification {
  Date dateCreated
  int status=0
  static belongsTo=[user:User]

  @Override
  public int compareTo(obj) {
     dateCreated.compareTo(obj.dateCreated)
  }
}

If I return the "User" object to a GSP, is there any way to get the count of all notifications where status=1.

Eg: user.notifications.size() (but where status=1)

Without having to return another separate notifications object.


Solution

  • You mention the word "transients" in the title, but nowhere else. Are you wanting to declare a transient property to do something like this?...

    class User {
        SortedSet notifications
        static hasMany=[notifications:Notification]
        static transients = ['numberOfStatusOnes']
    
        int getNumberOfStatusOnes() {
            notifications?.count { it.status == 1 } ?: 0
        }
    }