我正在使用grails 1.3.7。假设我们有2个域:新闻,主题,这些是实现:
class News {
static hasMany = [ topics : Topic ]
String title
....
}
class Topic {
String title
....
}
我们假设有一个有10个主题的新闻。什么是最好的查询以及如何以这种格式显示所有新闻?
[News1 title] [Topic1 title]
[News1 title] [Topic2 title]
...
[News1 title] [Topic10 title]
[News2 title] [Topic3 title]
[News3 title] [Topic6 title]
...
这是我到目前为止所拥有的:
def c = News.createCriteria()
def ret = c.list (max: size, offset: offset){
topic {
'in'('id', selectedTopicIds)
}
order("title", "desc")
}
// ret by this time contains 10 instances of News1
for (News r in ret){
log.info("title: ${r.title}")
// how can i maintain the order of r.topics on next loop?
log.info("topic: ${r.topicsiterator().next().title}")
}
您能告诉我最佳做法或解决此问题的任何提示吗?谢谢!
答案 0 :(得分:0)
我使用hql而不是标准来避免整个后期处理:
News.executeQuery("select news, topic from News as news inner join news.topics as topic group by news")
<强>更新强>
News.list().each { news ->
news.topics.sort { it.title }.each { topic ->
println "${news.title}: ${topic.title}"
}
}
第一个hql解决方案具有更好的性能,因为排序是由db完成的。