开发者

In GORM, how to maintain the order of 'hasMany' field for display purposes?

I'm using grails 1.3.7. Let's say we have 2 domains: News, Topic and these are the implementation:

class News {

    static hasMany = [ topics : Topic ]

    String title
    ....

}

class Topic {

    String title
    ....

}

Let's assume that there is a news that has 10 topics. what's the best query and how to display ALL news in this format?

[News1 title] [Topic1 title]
[News1 title] [Topic2 title]
...
[News1 title] [Topic10 title]
[News2 title] [Topic3 title]
[News3 title] [Topic6 title]
...

Here's what I have so far:

def c = News.createCriteria()
def ret = c.list (max: size, offset: offset){
    topi开发者_开发问答c {
        '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}")
}

Can you tell me the best practice or any tips to solve this? Thanks!


i'd use hql instead of criterias to avoid the whole post processing:

News.executeQuery("select news, topic from News as news inner join news.topics as topic group by news")

UPDATE

News.list().each { news ->
   news.topics.sort { it.title }.each { topic ->
        println "${news.title}: ${topic.title}"
   }
}

the first hql solution has the better performance, because sorting is done by the db.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜