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

…衆ロ難τιáo~ 提交于 2019-12-21 12:33:52

问题


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:


Try using a criteria:

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


来源:https://stackoverflow.com/questions/6959735/grails-how-to-find-by-a-record-by-its-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!