开发者

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 psue开发者_JS百科do-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


Try using a criteria:

def c = AlumLanguage.createCriteria()
def languages = c.get {
    eq('name', 'whatever-language')
    alumProfile {
        eq('id', 'jIi-hRi4cI')
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜