Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails, how to find by a record by its foreign key

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

like image 203
jason Avatar asked Aug 05 '11 16:08

jason


1 Answers

Try using a criteria:

def c = AlumLanguage.createCriteria()
def languages = c.get {
    eq('name', 'whatever-language')
    alumProfile {
        eq('id', 'jIi-hRi4cI')
    }
}
like image 102
Rob Hruska Avatar answered Oct 29 '22 19:10

Rob Hruska