如何在删除一对多关联中的多个边元素时调用beforeDelete事件?

时间:2014-09-10 15:34:18

标签: grails

我在这两个域类都有一对多关联

的PurchaseOrder

class PurchaseOrder {
  BigDecimal balance

  static constraints = {
    balance nullbale:false
  }

  List items
  static hasMany = [items:Item]

}

物品

class Item {
  String product
  Integer quantity
  BigDecimal price

  def beforeInsert() {
    def balance = purchaseOrder.balance ?: 0

    total = price * quantity
    purchaseOrder.balance = balance + total
  }

  def beforeDelete() {
    purchaseOrder.balance -= total
  }

  static belongsTo = [purchaseOrder:PurchaseOrder]
}

在PurchaseOrder类中是字段余额,需要在创建Item对象或更新或删除时计算此字段(余额)。

调用Item类中的beforeInsert事件并更新平衡但是当我尝试删除一个Item之前删除它没有被称为

我试图以这种方式删除项目

purchaseOrderInstance.removeFromItems itemInstance

这样就不会计算错误消息和余额属性

如果我尝试

itemInstance.delete(flush:true)

我收到此错误消息

Error initializing the application: deleted object would be re-saved by cascade (remove deleted object from associations): [ni.sb.Item#2]; nested exception is org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations): [ni.sb.Item#2]

我希望你能帮助我

1 个答案:

答案 0 :(得分:0)

它不会像这样工作。要从购买中delete()购买商品,您必须

purchase.removeFromItems (item)
item.delete ()

问题是removeFromItems()会清除belongsTo后退引用,而您的deleteBefore()事件会失败。

这种方法的另一个问题是,只要未保存购买并且您使用balance执行某项操作,balance就会出错。

最简单的方法是重新计算每次访问的余额:

class Purchase {
    BigDecimal balance

    BigDecimal getBalance () {
        BigDecimal total = 0
        items.each { Item item ->
            total += item.total ()
        }
        total
    }

    List items
    static hasMany = [items:Item]
}


class Item {
    String product
    Integer quantity
    BigDecimal price

    BigDecimal total () {
        price * quantity
    }

    // rest of code ...
}

我还建议您阅读gorm gotchas