Grails, how to find by a record by its foreign key
Asked Answered
I

1

6

I have two domains that are a part of a one-to-many relations ship. I was wondering how i can query the child for the parents FK? bellow is the psuedo-code for parent/child

Parent:

    class AlumProfile    {
String firstName
String lastName
    static hasMany = [alumLanguage  : AlumLanguage]


static mapping = {
    cache true
    id generator: 'assigned'

    columns {
        firstName   type:'text'
        lastName    type:'text'
    }

    //
}
static constraints = {
    firstName   (nullable:true)
    lastName    (nullable:true)
    }

    }

Child:

 class AlumLanguage {
String name
String level

static belongsTo = [alumProfile:AlumProfile]
static mapping = {
    cache true

    columns {
        name type:'text'
        level type:'text'
    }
}
static constraints = {
    name(nullable:true)
    level(nullable:true)
}
  }

Although I do not explicitly create the FK, grails takes care of creating it the MySQL DB on its own. But, when i want to query the child by the FK like this:

  if(AlumLanguage.findByNameAndAlumProfileId(language.'language'.toString(), 'jIi-hRi4cI')==null){
        //do something
 }  

I get an error: No property found for name [alumProfileId] for class [class mgr.AlumLanguage]

Any suggestions on how to accomplish this?

thanks jason

Impersonal answered 5/8, 2011 at 16:43 Comment(0)
O
7

Try using a criteria:

def c = AlumLanguage.createCriteria()
def languages = c.get {
    eq('name', 'whatever-language')
    alumProfile {
        eq('id', 'jIi-hRi4cI')
    }
}
Objection answered 5/8, 2011 at 18:19 Comment(4)
this returns a list. i need to have the AlumLanguages object returned, so that I can edit/delete instances of itImpersonal
Updated. However, if you're going to do it that way, you probably want to declare AlumProfile.alumLanguage as a Set to enforce unique members.Objection
Thanks, that did it! out of curiosity, what do you mean by "declare AlumProfile.alumLanguage as a Set"? Thanks again!Impersonal
@Impersonal - Actually, just ignore that statement. I'm not sure what I was thinking. By default it's a Set, anyway, so you shouldn't have to worry about anything.Objection

© 2022 - 2024 — McMap. All rights reserved.