我在grails项目中有两个实体
class Author {
String name
static hasMany = [books: Book]
}
class Book {
String title
int year
String isbn
}
当我删除Book时,我需要删除作者和关联表引用
但是当我做Book.delete(id)时,我就是这个堆栈跟踪
{"errors":"Hibernate operation: could not execute statement; SQL [n/a]; Cannot delete or update a parent row: a foreign key constraint fails
我是怎么做到的?
答案 0 :(得分:1)
在书中添加secoes
32
33
34
35
36
37
38
...
告诉GORM级联删除http://docs.grails.org/3.3.x/ref/Domain%20Classes/belongsTo.html
或者使用ORM dsl获取belongsTo
答案 1 :(得分:-1)
如果您想要删除本书(而不是实际删除作者和所有相关书籍),那么您需要执行以下操作:
更改您的Book类以引用作者:
class Book {
String title
int year
String isbn
Author author
static belongsTo = Author
}
然后在删除之前从作者中删除该书:
Book b = ? // get your book however you want here
def author = b.author
author.removeFromBooks(b)
b.delete()