Search code examples
grailsgrails-orm

Grails 2.5.0 - metaParams on Set?


I have the following class:

class User {
...
static hasMany = [data: MyData]
...
}

I would like to get user.data on a User object but filter the returned list using metaParams like in findAllBy (https://grails.github.io/grails-doc/latest/ref/Domain%20Classes/findAllBy.html).

Is this possible?


Solution

  • With a criteria query you can do something like this:

    def id = /* some User.id here */
    
    // http://grails.github.io/grails-doc/2.1.0/ref/Domain%20Classes/createCriteria.html
    def data = User.createCriteria().list(max: 10, offset: 100) {
        projections {
            property 'data'
        }
    
        eq 'id', id
    
        order 'something', 'desc'
    }
    

    If you end up with duplicate MyData instances, try using HQL instead. Like this:

    // https://grails.github.io/grails-doc/latest/ref/Domain%20Classes/executeQuery.html
    User.executeQuery 'select distinct u.data from User as u where u.id = :id', [id: id, max: 10, offset: 5]