Search code examples
grailsgroup-byprojection

Grails projections group by and count


Following are my two classes

class Users {
    String emailAddress
    String password
    //    String filename
    String firstName
    String lastName
    Date dateCreated
    Date lastUpdated
}

and

class SharedDocuments {
    Users author
    Users receiver
    Documents file
    static constraints = {

    }
}

I want to run a query similar to this one, essentially i want to get list of all the users along with count of documents they have authored

SELECT author_id, COUNT(SharedDocuments.id )FROM SharedDocuments 
  INNER JOIN users ON author_id = users.id
  GROUP BY author_id

This is what I have so far

def sharedDocumentsInstanceList = SharedDocuments.createCriteria().list(params){
    createAlias("author","a")
    eq("receiver.id",session.uid)  
    projections{
        groupProperty "author"
        count "id",'mycount'

    }
     order('mycount','desc')
    maxResults(params.max)
}

I have this 90% working, if i get rid of count or countDistinct I get list of distinct authors but what i want is authors along with the counts of documents. So when i add the count or countDistinct clause to this criteria I just get array of long!! like [2,3,4] what I want is [[author1,2],[author2,3] ...] How can i achive this I have already seen Grails: Projection on many tables?, Grails criteria projections - get rows count, Grails groupProperty and order. How it works?, but none of the answers seem to be solving my issue!


Solution

  • Projections with pagination has a bug where it only return the last field in the projections block. The current grails 2.1.5 has this bug fixed. Here is the reported bug http://jira.grails.org/browse/GRAILS-9644