Reputation: 1152
I know I can do Parent.childId
in Grails, but is there anything similar I can do to only load ids (proxies) for every children in a hasMany? I.e., something similar to Parent.childrenIds
?
In my case, the hasMany is mapped by a joinTable.
Upvotes: 0
Views: 255
Reputation: 1
I used "Querying Associations" and "Projection" to do this in the Parent domain object. (Query - GORM for Hibernate):
class Parent {
static hasMany = [childs: Child]
static mapping = {
childs joinTable: [name: 'parent_child', key: 'parent_id', column: 'child_id']
}
Collection<Long> getChildIds(){
withCriteria {
childs {
projections {
property 'id'
}
}
eq 'id', id
}
}
}
Upvotes: 0
Reputation: 1880
With a joinTable
in mind:
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 }
}
}
This works for a joinTable
mapped as such:
class Parent {
static mapping = {
childs joinTable: [name: 'parent_child', column: 'child_id', key: 'parent_id']
}
...
It's not pretty but I believe it's the best way considering the situation and requirement.
Upvotes: 0
Reputation: 3694
You can do this with a projection. e.g.
def result = Child.createCriteria().list {
projections {
property('id')
}
eq ('parent', parent)
}
This will return just the ids of the child objects.
Upvotes: 2