我试图通过使用ordinal属性重新排列询问给定问题的答案的顺序。因为ordinal属性的约束是unique,所以对于一个问题实例,我必须分配完全新的数字以避免使用unique constraint violation。
例如,如果一个问题有4个答案,答案的序数为1,2,3,4,我无法将序数更新为3,2,1,4,我必须更新它们7,6,5,8,以改变顺序。是否有一种在不违反唯一约束的情况下交换ordinal字段中的值的方法?
表格

应答域
class Answer {
DateTime dateCreated
DateTime lastUpdated
String body
Integer ordinal
String reason
static belongsTo = [question: Question]
static constraints = {
body blank: false
ordinal unique: 'question'
}
static mapping = {
question lazy: true
}
String toString() {
"Answer: $body"
}
Integer getNextOrdinal() {
Integer ordinal = Answer.createCriteria().get {
projections {
max "ordinal"
}
}
ordinal = ordinal ?: 1
return ordinal
}
}问题更新控制器
def update(Long id, Long version) {
def questionInstance = Question.get(id)
questionInstance.properties = params
def ordinals = params.list('ordinals')
questionInstance.answers.eachWithIndex{ Answer answer, int i ->
answer.ordinal = ordinals[i].toInteger()
}
if (!questionInstance.save(flush: true)) {
render(view: "edit", model: [questionInstance: questionInstance])
return
}
flash.message = "Question: '${questionInstance.body}' has been updated"
flash.messageType = "success"
redirect(action: "index", id: questionInstance.id)
}发布于 2014-08-20 18:14:20
为了理解这个错误,您需要考虑发生了什么。保存和刷新实例时,Hibernate将发布一系列更新。在这些更新过程中,非常有可能(正如您已经看到的)更新序号值与在刷新过程中尚未更新的现有值相冲突。
为了避免这种情况,您需要清空答案的集合,然后附加更新的实例。
因此,与目前的情况不同:
def ordinals = params.list('ordinals')
questionInstance.answers.eachWithIndex{ Answer answer, int i ->
answer.ordinal = ordinals[i].toInteger()
} 你需要更多的东西,比如:
def ordinals = params.list('ordinals')
def answers = []
// collect the existing answers, and update their ordinals
questionInstance.answers.eachWithIndex{ Answer answer, int i ->
answer.ordinal = ordinals[i].toInteger()
answers << answer
}
// clear the collection
questionInstance.answers.clear()
// add them back in again with the updated information
answers.each { questionInstance.addToAnswers(it) }这是我的头顶,所以用它作为你应该朝的方向的一个例子。
祝你们大学好运!
https://stackoverflow.com/questions/25411208
复制相似问题