Daddy Pumpkin
Daddy Pumpkin

Reputation: 484

Grails GORM : Find All with Associations

I'm trying to get all Users in a certain age range. I have a User table and a Profile table for each User.

Minimal User Domain Class:

class User {

  static hasOne = [profile: Profile]

}

Minimal Profile Domain Class:

class Profile {

  static belongsTo = [user: User]

  Integer age

  static constraints = {
    age(range: 18 .. 150)
  }

}

Minimal UserService Domain Class:

class UserService {

  def list() {

    def users = User.findAll{
      gender in whichGenderList
      profile.age in 18 .. 150 /* Problem */
    }

}

On the line with Problem I'm getting the following exception in browser:

URI /foo/browse
Class org.hibernate.QueryException
Message could not resolve property: profile_alias0 of: foo.Profile

Question: In UserService how can I select from each User's Profile table its age?

I'm using:

Thanks!

Upvotes: 0

Views: 434

Answers (2)

dsharew
dsharew

Reputation: 10665

use criteria query like this:

 def users = User.createCriteria().list(){
     inList('gender', whichGenderList)
     profile{
          inList('age', 18 .. 150)
     }

    }

Upvotes: 1

cfrick
cfrick

Reputation: 37008

If in doubt use HQL:

User.findAll(
    "from User u where u.gender in :genders and u.profile.age between :minAge and :maxAge",
    [genders: [], minAge: 18, maxAge: 150]
)

Upvotes: 0

Related Questions