【问题标题】:GORM cascade-delete offGORM级联删除
【发布时间】:2012-09-07 05:26:41
【问题描述】:

我有三个域模型Type1Type2Details,关系如下:

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

问题是当Type1 被转换为Type2 时,我无法将Type1.detail 转换为Type2.detail注意:Type1 和 Type2 只是@987654329 的子代@)。换句话说(在控制器中):

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

问题是,只更新type1Details,如何设置type1Details*.type1 = nulltype1Details*.type2 = type2

【问题讨论】:

    标签: grails grails-orm cascade


    【解决方案1】:

    在尝试了有关如何解决此问题的所有可能的说明序列后,我最终得到了这个可行的解决方案。从上面的问题中,我删除了所有与Type1相关的Details,从而删除了detail表上与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)
    }
    

    从上面的代码中,很清楚它是如何完成的。我知道这不是最好的解决方案,但我仍然可以接受更好的解决方案。

    【讨论】:

      猜你喜欢
      • 2014-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多