用于在 GORM 中查询关联的子查询

Ase*_*sal 5 grails hibernate subquery grails-orm

我在 GORM 中有以下域。

class Topic {
static hasMany = [resources: Resource, subscriptions: Subscription]
}

class Resource {
static belongsTo = [resourceOf: Topic]
}

class Subscription {
 static belongsTo = [subscriptionOf: Topic]
}
Run Code Online (Sandbox Code Playgroud)

我一直无法找到使用条件/命名子查询运行子查询的语法。例如,如何使用条件在 GORM 中编写以下查询。

select topic.id, 
(select count(*) from Resource where resourceOf.id = topic.id) as numRes,
(select count(*) from Subscription where subscriptionOf.id = topic.id) as numSubs
from topic
where topic.id in (<My topic ids>)
group by topic.id;
Run Code Online (Sandbox Code Playgroud)

这是非常基本的事情,但我无法找到相同的文档。

有谁知道如何使用 GORM 中的namedQueries 来完成此操作?

我的grails版本是2.4.4

Joh*_*ohn 2

您的查询是“给我匹配给定主题列表的主题及其各自的资源和订阅数量”。

(编辑以反映评论)我认为这可能对你有用:

def myTopicIds = ['1', '2']  // search for ids 1 and 2
def criteria = Topic.createCriteria()
def results = criteria.list() {
    'in'('id', myTopicIds)  // restrict results to only those matching your given ids
    projections {
        property("id")
        resources {
            countDistinct('id')   
        }
        subscriptions {
            countDistinct('id')   
        }
       groupProperty('id')
    }
}.collect {
        [
            topicId: it[0],
            numRes: it[1],
            numSubs: it[2]
        ]
    }
Run Code Online (Sandbox Code Playgroud)

收集更改了结果集合,并允许您将结果作为映射来引用,其中每个项目都有 3 个带有显示名称的键,否则您将不得不仅引用无名数组项目。