只从Grails中的hasMany中获取ID?
我知道我可以在Grails中执行只从Grails中的hasMany中获取ID?,grails,Grails,我知道我可以在Grails中执行Parent.childId,但是有没有类似的操作可以只为hasMany中的每个子级加载ID(代理)?例如,类似于父.childrenIds 在我的例子中,hasMany由一个joinTable映射。您可以使用。e、 g 这将只返回子对象的ID。记住一个连接表: def getChildIds(parentId) { Child.withSession { session -> def sql = new Sql(session.c
Parent.childId
,但是有没有类似的操作可以只为hasMany中的每个子级加载ID(代理)?例如,类似于父.childrenIds
在我的例子中,hasMany由一个joinTable映射。您可以使用。e、 g
这将只返回子对象的ID。记住一个
连接表
:
def getChildIds(parentId) {
Child.withSession { session ->
def sql = new Sql(session.connection())
sql.rows(
'select pc.child_id from parent_child pc where pc.parent_id = :parentId',
[parentId: parentId]
).collect{ it.child_id }
}
}
这适用于映射如下的联接表
:
class Parent {
static mapping = {
childs joinTable: [name: 'parent_child', column: 'child_id', key: 'parent_id']
}
...
这并不漂亮,但我相信这是考虑到情况和需求的最佳方式。没有那么优雅,但我确信
createCriteria()
解决方案是可能的。考虑到db表是如何与列中具有父id的子类进行映射的,可能会导致不考虑父id的获取,因此我不确定您可以获得多少。实际上,我正在使用joinTable来处理此特定关系-因此子id在单独的表中可用。如果Grails提供Parent.childrenIds或类似的文件,那么这个细节可能会在幕后处理。谢谢&回答得好。但是我正在为这个特殊的关系使用一个joinTable,所以我担心这不会立即解决它(父域在子域中不可用)。很抱歉,没有提到这一点,直到你回答我才意识到。我将接受这个答案,尽管我不会使用它,因为“不漂亮”部分:-)谢谢你的努力!
class Parent {
static mapping = {
childs joinTable: [name: 'parent_child', column: 'child_id', key: 'parent_id']
}
...