【发布时间】:2016-05-16 23:17:27
【问题描述】:
我有一个包含以下实体的应用:
主题:
class Topic {
UUID id
String description
String name
boolean visibility = true
// Relation
static hasMany = [tests:Test]
...
}
测试:
class Test {
UUID id
boolean active = true
String description
...
static hasMany = [evaluationsTest: Evaluation]
static belongsTo = [topic: Topic, catalog: Catalog]
}
当我向用户显示所有可见主题时,我请求查询:
def visibleTopics = Topic.findAllByVisibility(true, [sort:"name", order:"asc"])
此查询返回我,例如:[['English'], ['Spanish']]。然后,我可以向用户展示每个主题的完整信息。
但我还想向用户指出每个可见主题中的活动测试数。
例如:
English topic has 2 active test.
Spanish topic has a total of 2 test. One is active and the other is not.
German topic has not any active test.
然后我需要一个查询,其结果是:def activeTotalEachTopic = [[2],[1],[0]],我可以将activeTotalEachTopic 变量传递给视图 (.gsp)。
解决方案:
从我可以获得所有可见主题的第一个查询中,我得到了活动测试的数量。
def visibleTopics = Topic.findAllByVisibility(true, [sort:"name", order:"asc"])
def numberActiveTest = []
activeTopics.each { topic ->
def result = Test.findAllByTopicAndActive(topic, true).size()
numberActiveTest.push(result)
}
我将两个变量都传递给视图。
render view: 'home', model: [activeTopics: activeTopics, numberActiveTest: numberActiveTest]
【问题讨论】:
标签: grails criteria grails-2.0 hibernate-criteria grails-domain-class