2011-07-27 49 views
0

我正在使用grails 1.3.7。假設我們有2個域:新聞,主題,這些是實現:在GORM中,如何維護'hasMany'字段的顯示順序?

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

我會使用HQL,而不是審覈規定,以避免整個後處理:

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

第一HQL解決方案具有更好的性能,因爲排序是通過做分貝。

+0

是的,這實際上是我的其他選擇,但我想如果有其他方法可以做到這一點,而不使用SELECT語句和executeQuery。 – firnnauriel

+0

我更新了答案 – hitty5

+0

看起來不錯,但請注意有一個WHERE條件(someIdlist中的主題ID)。 WHERE條件使其具有挑戰性。 – firnnauriel