我有以下(简化的)域类
class Filter {
String name
static hasMany = [answers:Answer]
static belongsTo = [user:User]
}
class User {
String name
static hasMany = [answers:Answer, filters:Filter]
}
class Answer {
String text
}
然后我向用户添加完美的答案。当我删除用户的1个答案时,会出现问题:
def delete = {
def answer = Answer.get(params.id)
def users = User.withCriteria() {
answers{
eq("id", answer.id)
}
}
for (user in users)
user.removeFromAnswers(answer)
answer.delete(flush:true)
redirect(action:"index")
}
这里发生的是所有用户 - >答案关联被删除。
我只想删除这个答案,并且因为所有关联都会使用答案。
我知道这与丢失的belongsTo有关,但我不能使用它,因为ansswer可以属于用户或过滤器...
答案 0 :(得分:0)
您可以添加belongsTo
将其设置为nullable
:
class Answer {
String text
static belongsTo = [user:User, filter:Filter]
static constraints = {
user nullable:true
filter nullable:true
}
}
然后直接在Controller中删除Answer
:
def delete = {
def answer = Answer.get(params.id)
answer.delete(flush:true)
}
GORM将为您处理剩下的级联。