Grails,如何通过其外键记录查找

时间:2011-08-05 16:43:29

标签: hibernate grails grails-domain-class grails-controller

我有两个域是一对多关系的一部分。我想知道如何向孩子询问父母FK? bellow是父/子的伪代码

父:

    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)
    }

    }

子:

 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)
}
  }

虽然我没有明确创建FK,但grails会自己创建MySQL DB。但是,当我想通过FK查询孩子时:

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

我收到错误:找不到类[alumProfileId]的类[class mgr.AlumLanguage]的属性

有关如何完成此任务的任何建议?

感谢 杰森

1 个答案:

答案 0 :(得分:7)

尝试使用criteria

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