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

2019-04-07 14:04发布

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

1条回答
小情绪 Triste *
2楼-- · 2019-04-07 14:40

Try using a criteria:

def c = AlumLanguage.createCriteria()
def languages = c.get {
    eq('name', 'whatever-language')
    alumProfile {
        eq('id', 'jIi-hRi4cI')
    }
}
查看更多
登录 后发表回答