我正在使用Grails,并且我有一个域模型,该模型具有多个hasMany属性到同一个域类,如下所示:
static hasMany = [ posts : Post, likes : Post, dislikes : Post ]
我遇到的问题是,当我在帖子列表中添加内容时,它也以某种方式进入了“喜欢”和“不喜欢”列表。至少,当我遍历每个列表时,它就是这样。
我认为问题在于我的Post域中也存在以下关系:
static belongsTo = [ contributer : Contributer ]
配置这些关系以使模型正常工作的最佳方法是什么?有什么建议么?
@韦恩,
我也尝试使用您的测试,并且测试成功通过。因此,我唯一能想到的是PostController中的save方法出了点问题。我已经在下面粘贴了相关的代码(我正在使用Spring Security Core插件,而我的Contributer类扩展了使用该插件创建的User类):
@Secured(['IS_AUTHENTICATED_FULLY'])
def save = {
def props = [title:params.title, post:params.post, category:Category.get(params.category.id)]
def user = Contributer.get(springSecurityService.principal.id)
def postInstance = new Post(props)
postInstance.contributer = user
if (postInstance.save(flush: true)) {
flash.message = "${message(code: 'default.created.message', args: [message(code: 'post.label', default: 'Post'), postInstance.id])}"
redirect(action: "show", id: postInstance.id)
}
else {
render(view: "create", model: [postInstance: postInstance])
}
}
这里有什么特别的地方吗?
最佳答案
问题是您在帖子和贡献者之间有一对多的关系(帖子有一个作者,作者有很多帖子),并且帖子和贡献者之间有两个多对多的关系(帖子有很多喜欢者,喜欢很多帖子的喜欢者)(帖子有很多不喜欢的人,不喜欢的人不喜欢很多职位)。 Post中的belongsTo
确实说明了该行为,但是删除它并不能解决问题,仅创建其他问题即可。最终结果是,GORM约定将达不到要求,因此您必须告诉GORM如何不同地表现或建模事物。
有几种选择,但是让我想到的是,将投票与发布分开建模,并使其成为参与者,使hasMany
likeVotes和hasMany
dislikeVotes
class Vote {
// for illustration here, you need to think about the
// cascading behavior that makes sense and model it if you decide
// to go this route.
belongsTo = [post, contributor]
}
class LikeVote extends Vote {
}
class DislikeVote extends Vote {
}
GORM会将其建模为一个带有歧视者列的投票表,以区分好恶。这样您就可以消除喜欢,不喜欢和创作的帖子之间的冲突。
然后在贡献者中
hasMany = [likes:LikeVote, dislikes:DislikeVote, posts:Post]
关系现在已经清除:
GORM可以理解这些关系,并且会适本地表现。
如果您不喜欢此选项,则下一步将是为数据库结构指定自定义映射,然后使用
mappedBy
区分各种关系。如果您绝对希望让撰稿人以三种不同的方式与Post直接相关,则可以采用这种方法。
关于grails - 多个hasMany与Grails中的同一个域类有关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7536669/