从hasMany关联中删除元素不起作用

时间:2014-03-04 11:29:16

标签: grails gorm

致电ArrayList#remove()ArrayList#removeAll()无效。为什么会这样?

class Category {
    static hasMany = [elems: Elem]
    // ..
}

class Elem {
    static belongsTo = Category
    // ..
}

// ExampleController.groovy
def saveCategory(/* args */) {
    def category = categoryService.get.. // get some category object
    def elem = elemService.getElem(1)    // get some element that's in the category
    category.elems.remove(elem)  // *How to get this working*? Returns false as the object is not getting removed.
    category = categoryService.saveCategory(category)
    JSON.registerObjectMarshaller(Category) {
        def map = [:]
        map['id'] = it.id
        map['elems'] = it.elems
        return map
    }
    JSON.registerObjectMarshaller(Elem) {
        def map = [:]
        map['id'] = it.id
        return map
    }
    render(['category': category] as JSON)
}

感谢。

2 个答案:

答案 0 :(得分:2)

处理此问题的官方方法是使用addTo*removeFrom*方法。你可能想要研究一下,他们正在处理这个问题。

http://grails.org/doc/latest/ref/Domain%20Classes/addTo.html

http://grails.org/doc/latest/ref/Domain%20Classes/removeFrom.html

答案 1 :(得分:0)

您之后是保存category实例吗?

category.elems.remove(elem)
category.save()