Grails:每当删除主域对象时,如何删除关联的域?

时间:2015-10-07 01:13:22

标签: grails gorm

我希望,每当删除某个域时,都会删除所有 hasMany 域和关联的域。我有以下域名结构。

class Book {
    static hasMany = [ bookOptions: BookOption ]
}

class Category {
    static hasMany = [ options: Option ]
    static mapping = {
        options cascade: "all-delete-orphan"
    }
}

class Option {
    static belongsTo = [ category: Category ]
}

BookOption {
    Option option
    static belongsTo = [ book: Book, category: Category ]
}

我想删除所有选项 bookOptions ,并删除 Book BookOption 之间的关联< strong>类别已删除。

目前使用选项级联:“all-delete-orphan”,删除类别时会删除所有选项,但我会遇到对 BookOption 的参照完整性约束违规。

一个选项是手动查找所有 bookOptions ,遍历列表并删除每个。

def bookOptions = BookOption.findAllByCategory(category)
bookOptions.each{ bookOption ->
    def book = bookOption.book
    book.removeFromBookOptions(bookOption)
    bookOption.delete(flush:true)
}

category.delete(flush:true)

是否有更多Grails方式执行此操作?或者是我定义标准的选项?

2 个答案:

答案 0 :(得分:0)

我认为在类别中应该有很多bookOptions。请检查创建的表是MyISM还是InnoDB。

答案 1 :(得分:0)

def books = Books.findAllByCategories(category)
books?.each{ book ->
 book?.categories?.clear()
 book?.bookOptions?.clear()
}