一个简单的博客应用程序,Grails 1.3.9 和 MySQL,两个域类 BlogPost 和 Tag 之间的多对多关系
class BlogPost {
String title
String teaser
String body
Date updated
Category category
Integer priority
static hasMany = [comments:Comment,tags:Tag]
static belongsTo = [Category,Tag]
static searchable = true
String toString() {
"$title"
}
static constraints = {
title(nullable:false,blank:false,lenght:1..50)
teaser(nullable:false,blank:false,lenght:1..100)
body(nullable:false,blank:false,maxSize:5000)
updated(nullable:false)
category(nullable:false)
priority(nullable:false)
}
}
class Tag {
String name
String description
static hasMany = [blogpost:BlogPost]
static searchable = true
String toString() {
"$name"
}
static constraints = {
name(nullable:false,blank:false)
description(nullable:false,blank:false)
}
}
Hibernate 在 MySQL 中创建三个相关表:blog_post、tag 和 tag_blogpost
现在,如果我创建与博文 Y 相关的标签 X,然后删除 Y,tag_blogpost 表中将保留一个孤立的行,并且标签 X 的显示 View 会抛出异常“不存在具有给定标识符的行:[。 ..]”
如何自动删除(级联)tag_blogpost 表中的孤立行?
最佳答案
在您的模型中,BlogPost 和 Tag 之间存在两种关系是否正确?要创建一个 BlogPost 必须有一个标签,也可以是 n 个标签?
您创建的标签是作为标签属性关联到 BlogPost 还是在标签列表中?
如果它在标签列表中,我认为 Grails 认为您的模型是多对多的,并且根据 docs :
Many-to-many: only saves cascade from the "owner" to the "dependant", not deletes.
在帖子标签模型中思考我认为你的方法可以是多对多关系并手动处理标签的删除,删除之前的帖子。如果您真的需要在帖子中至少添加一个标签,在 BlogPost 的 View 中,您可以强制用户选择一个标签。
关于mysql - Grails 删除孤儿多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12409423/