我知道我可以在 Grails 中做
Parent.childId
,但是我可以做类似的事情来只为 hasMany 中的每个孩子加载 ids (代理)吗?即,类似于 Parent.childrenIds
?
在我的例子中,hasMany 由 joinTable 映射。
您可以通过投影来做到这一点。例如
def result = Child.createCriteria().list {
projections {
property('id')
}
eq ('parent', parent)
}
这将仅返回子对象的 id。
牢记
joinTable
:
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 }
}
}
这适用于这样映射的
joinTable
:
class Parent {
static mapping = {
childs joinTable: [name: 'parent_child', column: 'child_id', key: 'parent_id']
}
...
这并不漂亮,但我相信考虑到情况和要求,这是最好的方法。
我使用“查询关联”和“投影”在父域对象中执行此操作。 (查询 - 用于 Hibernate 的 GORM):
class Parent {
Collection<Long> getChildIds(){
withCriteria {
childs {
projections {
property 'id'
}
}
eq 'id', id
}
}
}