1

假设我有两个域对象,文档和作者

Class Document {
    Author author
    String title
}

Class Author {

    String lastName
    String firstName

    String toString() {

        return lastName + ", " + firstName
    }
}

视图 list.gsp 看起来像这样:

<g:sortableColumn property="title" title=... />
<g:sortableCOlumn property="author" title=... />

....

<td>${fieldValue(bean: documentInstance, field: "author"}></td>
<td>${fieldValue(bean: documentInstance, field: "title"}></td>

表中显示的值按预期工作 - 表行将在 documentInstance.title 旁边显示作者为 (l​​astName, firstName)。

但是,单击 Author 列标题进行排序会导致“文档”按 author.id 排序。

按 author.toString() 或“author.lastName, author.firstName”而不是按 author.id 排序的最方便的方法是什么?

如果可能的话,我宁愿避免回退到 .withCriteria{} - 我有四个不同的列需要此功能,而且看起来会变得混乱。

4

2 回答 2

3

您可以使用派生属性创建一个虚拟列进行排序:

Class Author {

    String lastName
    String firstName
    String sortingName

    static mapping {
        // modify the SQL formula to use your DB's concatenation operator
        sortingName formula: "`LAST_NAME` || ',' || `FIRST_NAME`)" // Standard SQL
    }

    String toString() { sortingName }
}

然后将您的列设置为sortingName

<g:sortableColumn property="author.sortingName" title=... />

(我在这里有点猜测,但我认为这应该可行。)

于 2012-04-15T15:57:59.717 回答
2

我只是一个 Grails 初学者,所以也许我的答案不是最佳的,但这对我来说是最简单的方法:

而不是使用Document.list(params)我使用的Document.findAll(). 值得一提的是,在我的应用程序中,我的列表中确实需要某种过滤器,所以这findAll()是最好的方法。无论如何,我会这样做:

Document.findAll( "from Document as d order by d." + params.sort + ' ' + params.order, params ) //supports pagination

在视图中:

<g:sortableCOlumn property="author.lastName" title=... />
于 2012-04-15T16:14:24.223 回答