使用Grails在视图中订购对象集合

时间:2014-03-09 14:16:20

标签: grails collections

当我尝试在视图中显示对象集合时,我遇到了一个问题,它们以随机顺序返回,每次刷新页面时都会有所不同。

以下是一个例子:

class Author{
    ...
    static hasMany = [books:Book]
}
class Book{
    ...
    static belongsTo = [author:Author]
}

在作者的一个观点中,我想做一些像:

<g:each in="${authorInstance.books}" var="book">
    //render book template or whatever...
</g:each>

当我这样做时,每次返回的书籍集合的顺序不同。我怎样才能每次只按ID排序集合?

1 个答案:

答案 0 :(得分:3)

有几种方法可以对此集合进行排序。这一切都取决于你想要进行排序的地方。

首先,您可以在域中定义集合的默认顺序:

class Author {
    static hasMany = [books: Book]
    static mapping = {
        books sort: 'id', order: 'asc'
    }
}

或者,您可以在GSP中对集合进行排序:

<g:each in="${authorInstance.books.sort{it.id}}" var="book">
    //render book template or whatever...
</g:each>