1
ORDER BY我有這樣的關係:如何Grails的HQL語句
class Foo {
static hasMany = [bars: Bar, things: Thing]
}
class Bar {
// Has nothing to tie it back to Foo or Thing
}
class Thing {
// Has nothing to tie it back to Foo or Bar
}
我有下列參數,其中大部分是用於與flexigrid分頁下面的查詢。該查詢通過Foo
獲取與Bar
的特定實例關聯的所有Thing
實例。所以,如果我的Bar
實例是Bar1
會期望我的查詢返回Thing1
和Thing2
:
def obj = Bar.get(1) // Get Bar1
def max = params.int("max") ?: 100 // Default max returned results is 100 unless otherwise specified
def offset = params.int("offset") ?: 0 // Default offset is 0 unless otherwise specified
def sortname = params.sortname ?: "id" // Default is id, but could be any member of Thing that is not a "hasMany"
def sortorder = params.sortorder ?: "ASC" // Default is ASC, but could be DESC
def namedParams = [ obj: obj, max: max, offset: offset ]
Thing.executeQuery("SELECT DISTINCT f.things FROM Foo f INNER JOIN f.things things INNER JOIN f.bars bars WHERE bars =:obj ORDER BY ${sortname} ${sortorder}", namedParams)
休眠不允許命名參數的使用指定ORDER BY
條款,所以我只是插入的字符串。問題在於結果不按我指定的順序排列。當使用ORDER BY id
Grails告訴我id
是不明確的。
知道變量sortname
將始終是Thing
的成員,我如何指定要排序的內容?
一些我已經試過的東西:
ORDER BY Thing.id // Fail
ORDER BY f.things.id // Fail
ORDER BY things.id // FAIL!
太棒了!感謝你的幫助。 HQL並不是一個與SQL有很大差異的地方,但它足以導致我一些問題。雖然我現在抓住了它,但:) – ubiquibacon