Grails投影按组分组和计数

3
以下是我的两个类:
class Users {
    String emailAddress
    String password
    //    String filename
    String firstName
    String lastName
    Date dateCreated
    Date lastUpdated
}

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

    }
}

我希望运行类似于这个的查询,实际上我想要获取所有用户的列表以及他们撰写的文档数量。

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

这是我目前的进展

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)
}

我已经完成了90%的工作,如果我去掉countcountDistinct,我将得到不重复作者列表,但我想要的是作者以及他们所写文档的数量。因此,当我将count或countDistinct子句添加到这个条件中时,��只会得到一个长数组!类似于[2,3,4],我想要的是[[author1,2],[author2,3]...]。我该如何实现这个目标?我已经看过Grails: Projection on many tables?Grails criteria projections - get rows count, Grails groupProperty and order. How it works?,但是没有一个答案似乎解决了我的问题!
3个回答

1

使用分页的投影存在一个问题,它只返回投影块中的最后一个字段。当前的grails 2.1.5已经修复了这个错误。这是报告的错误http://jira.grails.org/browse/GRAILS-9644


0

你不能只是使用countBy*吗 - 就像这样

    SharedDocuments.countByAuthorAndReceiver(user, receiver)

0
如果您希望结果与您查询中描述的一样,那么您需要作者的ID或任何其他特定属性,例如电子邮件。

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

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

无论我做什么,我的结果集中只有计数而没有其他信息。在你给我的代码中打印 sharedDocumentsInstanceList 会产生 '[2, ]' 的输出。 - undefined
我正在做几乎完全相同的事情,但是使用了一个命名查询,并且没有maxResults,在我这里它运行得很好 :(。顺便说一下,我甚至没有使用author.id,只是对作者进行分组也应该可以工作。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接