我有这样的关系:

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分页。该查询通过 Thing获取与 Bar的特定实例相关联的 Foo的所有实例。因此,如果我的 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 ) 

Hibernate不允许使用命名参数来指定 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! 

请您参考如下方法:

查询应为:

SELECT DISTINCT thing FROM Foo f  
INNER JOIN f.things thing  
INNER JOIN f.bars bar  
WHERE bar = :obj  
ORDER BY thing.id 

也就是说,您应该在select子句中使用实体的别名而不是其路径,并在order by子句中使用相同的别名。


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!