PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

[FIXED] How can I get objects based off of certain associations?

 October 21, 2022     grails, grails-orm, groovy, has-many     No comments   

Issue

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.



Answered By - Jeff Scott Brown
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing