Search code examples
grails

Fetch only the ids from a hasMany in Grails?


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.


Solution

  • 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.