Grails/GORM:创建一对一的可选关系
我正在设计一个系统,用户之间的帖子/讨论可以升级为门票。在一个特定的地方,我试图创建一种一对一的可选关系,但遇到了某些问题。下面给出了受到关注的实体的精简版本。
规则:
- 如果需要,帖子可以成为票证。 (可选)
- 票证必须有一个帖子。 (强制)
Post.groovy
class Post {
String title
String description
String postedBy
Ticket ticket
static hasMany = [comments: Comment]
static constraints = {
title(blank:false)
description(blank:false)
postedBy(blank:false)
ticket (nullable:true,unique:true)
}
}
Ticket.groovy
class Ticket {
String title
String description
String postedBy
Post post
static hasMany = [responses: Response]
static constraints = {
title(blank:false)
description(blank:false)
postedBy(blank:false)
post (nullable:false,unique:true)
}
}
这在某种程度上有效。我可以:
- 创建一个帖子,将票证属性保留为空 如果该帖子升级为票证,
- 我可以显式设置该帖子的票证属性以指向父票证。
但是,此映射不是在域级别强制执行的。它为 Ticket1 指向 Post1,但 Post1 指向 Ticket2 的情况留下了余地。
我尝试在 Ticket 类中使用 static hasOne = [post: Post]
但后来了解到它要求存在 static ownsTo = [ticket: Ticket ]
在 Post 类中,这变成了强制性的一对一关系,这不是我想要的。
在这种场景下有没有办法实现这种1对1的可选映射呢?任何指示都会非常有帮助。
I'm designing a system in which posts/discussions between users can be upgraded to become tickets. At one particular place I'm trying to create a one-to-one optional relationship but am running into certain issues. A condensed version of the entities in the spotlight is given below.
Rules:
- A Post can become a Ticket if required. (optional)
- A Ticket must have a Post. (mandatory)
Post.groovy
class Post {
String title
String description
String postedBy
Ticket ticket
static hasMany = [comments: Comment]
static constraints = {
title(blank:false)
description(blank:false)
postedBy(blank:false)
ticket (nullable:true,unique:true)
}
}
Ticket.groovy
class Ticket {
String title
String description
String postedBy
Post post
static hasMany = [responses: Response]
static constraints = {
title(blank:false)
description(blank:false)
postedBy(blank:false)
post (nullable:false,unique:true)
}
}
This works to some extent. I can:
- Create a Post leaving the ticket attribute null If and when the post is upgraded to become a ticket
- I can explicitly set the Post's ticket attribute to point to the parent ticket.
However, this mapping isn't enforced at the domain level. It leaves room for a situation where Ticket1 points to Post1, but Post1 points to Ticket2 instead.
I tried using a static hasOne = [post: Post]
in the Ticket class but later learned that it mandates the presence of a static belongsTo = [ticket: Ticket]
in the Post class and this becomes a mandatory 1-to-1 relationship which is not what I'm looking for.
Is there a way to achieve this 1-to-1 optional mapping in this scenario? Any pointers would be most helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以考虑制作一个自定义验证器,例如
这可以解决您的问题吗?
You could consider making a custom validator like
Would this solve your problem?