Mám dva subjekty v grails projekte
class Author {
String name
static hasMany = [books: Book]
}
class Book {
String title
int year
String isbn
}
Keď som vymazať Book musím odstrániť autora a pridružené tabuľky odkazy
Ale keď som si Book.delete (id) som bol tento stacktrace
{"errors":"Hibernate operation: could not execute statement; SQL [n/a]; Cannot delete or update a parent row: a foreign key constraint fails
Ako to robím?
odpovede:
1 pre odpoveď č. 1Pridaj belongsTo
k knihe povedať GORM kaskádové vymazať http://docs.grails.org/3.3.x/ref/Domain%20Classes/belongsTo.html
Pre viac možností použite ORM dsl http://gorm.grails.org/6.1.x/hibernate/manual/index.html v sekcii 8.2.9. Custom Cascade Behaviour
-1 pre odpoveď č. 2
Ak chcete jednoducho vymazať knihu (a nie vlastne odstrániť autora a všetky súvisiace knihy), potom musíte urobiť niečo ako:
Ak chcete mať odkaz na autora, zmeňte svoju triedu knihy:
class Book {
String title
int year
String isbn
Author author
static belongsTo = Author
}
Pred odstránením knihy potom odoberte knihu od autora:
Book b = ? // get your book however you want here
def author = b.author
author.removeFromBooks(b)
b.delete()