5.2.1.1 Many-to-one和one-to-one - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith
Version: null
5.2.1.1 Many-to-oneå’Œone-to-one
A many-to-one relationship is the simplest kind, and is defined with a property of the type of another domain class. Consider this example:Example A
class Face {
Nose nose
}class Nose {
}Face to Nose. To make this relationship bidirectional define the other side as follows:Example B
class Face {
Nose nose
}class Nose {
static belongsTo = [face:Face]
}belongsTo setting to say that Nose "belongs to" Face. The result of this is that we can create a Face, attach a Nose instance to it and when we save or delete the Face instance, GORM will save or delete the Nose. In other words, saves and deletes will cascade from Face to the associated Nose:new Face(nose:new Nose()).save()
Face:new Nose(face:new Face()).save() // will cause an error
Face instance, the Nose will go too:def f = Face.get(1) f.delete() // both Face and Nose deleted
hasOne property on the owning side, e.g. Face:Example C
class Face {
static hasOne = [nose:Nose]
}class Nose {
Face face
}nose table inside a column called face_id. Also, hasOne only works with bidirectional relationships.Finally, it's a good idea to add a unique constraint on one side of the one-to-one relationship:class Face {
static hasOne = [nose:Nose] static constraints = {
nose unique: true
}
}class Nose {
Face face
}
