Grails查询map其中object1 hasMany object2

时间:2014-03-29 18:44:58

标签: grails hql gorm

我想做这样的查询:

我有Tale hasMany secondaryTags

我想要做的查询如下:

def query = 'select new map(title as title,
                            mainTag as mainTag, 
                            secondaryTags as secondaryTags) from Tale order by rand()';
def result = Tale.executeQuery(query, [max: 3])

但由于secondaryTagsCollection的{​​{1}},它不起作用。有谁知道我是怎么做到的?

提前多多感谢!

1 个答案:

答案 0 :(得分:0)

需要连接才能获取关联。尝试此查询,它应该工作:

select new map( tale.title as title,
                tale.mainTag as mainTag, 
                sts as secondaryTags ) 
       from Tale as tale
       inner join fetch tale.secondaryTags as sts
       order by rand()

因为您正在寻找map。否则

select tale from Tale as tale
       inner join fetch tale.secondaryTags
       order by rand()

应足以从一个查询中获取所需内容。另请注意,使用inner join fetch,这意味着上述查询将eagerly从同一查询中的故事中获取关联secondaryTags,而不是触发另一个查询以获取关联{{1发布。要见证这一事实,请在tale.secondaryTags中启用日志记录(logSql = true)并检查上述原则的行为。