GORM cascade-delete off
문제
I have three domains models Type1
, Type2
and Details
following the relationship below:
class Type1 {
static hasMany = [detail: Detail]
}
class Type2 {
static hasMany = [detail: Detail]
}
class Detail {
Type1 type1
Type2 type2
static belongsTo = [Type1, Type2]
static constraints = {
type1(nullable:true)
type2(nullable:true)
}
}
The problem is that I can't get Type1.detail
to be transfered to Type2.detail
whenever Type1
is to be converted to Type2
(Note: Type1 and Type2 is only a child of java.lang.Object
). In other words (in a controller):
Type1 type1 = Type1.get(params.id)
List type1Details = Detail.findAllByType1(type1)
type1.detail.clear()
Type2 type2 = new Type2()
// transfer other properties of type1 to type2
type1Details.each { type2.addToDetail(it) }
if(type2.save(flush:true) {
type1.save(flush:true)
type1.delete(flush:true)
}
The question is, only updating type1Details
, how can we set type1Details*.type1 = null
and type1Details*.type2 = type2
?
해결책
After trying all the possible sequences of instructions on how to solve this problem, I end up with this working solution. From the question above, I have removed all Details
related to Type1
thus deleting the record on the detail
table related to Type1.detail
.
Type1 type1 = Type1.get(params.id)
Type2 type2 = new Type2()
// transfer other properties of type1 to type2
type1.detail.each {
Detail element = (Detail) it
element.type1 = null
element.type2 = type2
}
type1.detail.clear()
if(type2.save(flush:true)) {
type1.delete(flush:true)
}
From the code above, it's clear how it is done. I know this isn't the best solution, but I can still accept better solutions.