register
other register

Tuesday, June 30, 2009

Digesting belongsTo


class Face {
String name
Nose nose
static constraints = {
nose (nullable: true)
}

String toString() {
return name
}
}

class Nose {
String name
static belongsTo = [face: Face]
String toString() {
return name
}
}

def a = new Face(name: 'joe')
def b = new Nose(name: 'blog')
a.b = b
a.save(flush: true)
b.save(flush: true)


// test
def face = Face.findWhere (name: 'joe')
println face.nose

def nose = Nose.findWhere(name: 'blog')
println nose.face

// You must set nullable: true for nose in the constraint, otherwise the save won't work and it doesn't throws any exception
face.nose = null
face.save()
println face



In the above relationship, the foreign key (i.e. nose_id) will added in the Face side. But you can still get hold of face from the nose, because nose belongsTo face.

No comments: