Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

withCriteria two level deep association eager fetch grails


I'd like to eager load a structure, two levels deep in an association chain. Something along the lines of:

class TopLevel {
    String name

    LevelOne levelOne
}    

class LevelOne {
    String name

    LevelTwo levelTwo
}

class LevelTwo {
    String name
}

I'd like to load the entire structure. Searching around I found this example, but it didn't work. The "println" generated a query to the LevelTwo table.

def result = TopLevel.withCriteria {
    eq('name', 'test')
    fetchMode "levelOne", FetchMode.JOIN
    levelOne {
        fetchMode "levelTwo", FetchMode.JOIN
    }
}

println result.levelOne.levelTwo.name

Appreciate any help!
- Steve

like image 888
ptsw Avatar asked Nov 14 '10 03:11

ptsw


1 Answers

Got it working. Here's the secret sauce:

def result = TopLevel.withCriteria {
    eq('name', 'test')
    fetchMode 'levelOne', FetchMode.JOIN
    fetchMode 'levelOne.levelTwo', FetchMode.JOIN
    fetchMode 'levelOne.levelTwo.levelThree', FetchMode.JOIN
}
like image 200
ptsw Avatar answered Oct 05 '22 03:10

ptsw