gpt4 book ai didi

grails - 了解 grails 中的 hasMany 行为以及如何保存关系

转载 作者:行者123 更新时间:2023-12-02 14:41:07 26 4
gpt4 key购买 nike

我正在制作一个模型,其中 User 填写许多调查问卷,并将答复保存到 Questionresponse。我在使用 grails 2.5.2

测试 1

所以我有两个模型

class User {
String username
...
static hasMany = [reponse: QuestionResponse]
}

class QuestionResponse {
String question_1
String question_2
...
}

通过以上操作,创建了一个新的数据库表:user_questionresponse,其中包含两列 user_questionresponses_idquestionresponse_id。这似乎是我想要的。用户会有很多问题响应,这些关系将保存在此表中。但是,我找不到如何将数据保存到该表中。

例如,如果我这样做:

def user = springSecurityService.currentUser
def questionnaire = new QuestionResponse(question_1: "foo", question_2: "bar")
//How do I link the user to this newly created questionnaire?
user.addToResponse(q).save(flush: true) //DOES NOT WORK.

Test2(只需添加 belongsTo)

class User {
String username
...
static hasMany = [reponse: QuestionResponse]
}

class QuestionResponse {
String question_1
String question_2
static belongsTo = [user: User]
...
}

如果我将 belongsTo 添加到 QuestionResponse,则会在数据库中创建一个新列 user_id。现在,如果我运行与上面相同的代码,此 user_id 列的 ID 将填充为当前用户的 ID。但是,关系表 user_questionresponse 仍然是空的。

我知道 Burt 提到的方法,但我认为只有 ManyToMany 关系才需要这种方法。如果所有关系都需要这样做,那为什么不默认呢?

最佳答案

在第一种情况下,User 和 QuestionResponse 之间存在 OneToMany 关系,没有一方是该关系的所有者。在这种情况下,为了维护 User 和 QuestionResponse 之间的关系,需要第三个表。要持久化数据,您需要执行以下操作:

userInstance.addToResponse(new QuestionResponse(question_1: "foo", question_2: "bar")).save(flush: true, failOnError: true)

你正在执行 user.addToReponse(q) 而不是它应该是 user.addToReponse(questionnaire),如果它不是错字并且数据实际上没有被存储,然后通过将 failOnError 参数添加到 save() 方法来进行检查。有时 grails save() 方法静默失败,它应该告诉您是否是这种情况。

在第二种情况下,您已将父级添加到关系中,这意味着您不需要第三个表来维护关系。在这种情况下,Grails 不会创建和填充第三个表。

关于grails - 了解 grails 中的 hasMany 行为以及如何保存关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34250685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com