Search code examples
grailsgroovygrails-ormhas-many

How can I get objects based off of certain associations?


I have the following domain classes (Only trying to show what is needed to get the idea) :

class Scholarship {

   static hasMany = [grades:Grade]
}

and

class Grade {

   String id
   String description
}

In words I would like to, "Get all scholarships where the associated grade_id = myId". I would like to accomplish this using grails domain classes and not using sql. Any help appreciated


Solution

  • Are you looking for something like this?...

    def results = Scholarship.withCriteria {
        grades {
            // myId must be defined somewhere above...
            idEq myId
        }
    }
    

    EDIT

    A comment below adds to the original question and asks what if another relationship was expressed like this...

    class Scholarship {
        static hasMany = [grades:Grade,majors:Major]     
    }
    

    The query I show above would still be exactly the same. The fact that there is a majors collection would not be relevant unless you wanted to include some attribute of Major to also be part of the criteria, which could look something like this...

    def results = Scholarship.withCriteria {
        grades {
            // myId must be defined somewhere above...
            idEq myId
        }
    
        majors {
            // only return Scholarship instances which
            // contain a Major with the name 'Mechanical Engineering'
            eq 'name', 'Mechanical Engineering'
        }
    }
    

    I hope that helps.