据我所知,SEARCH目前不支持在使用OnConflict条款时自动更新乐观锁版本列.
当您将OnConflict Clause与UpdateAll一起使用时,SERM会生成一个UPSERT声明,该声明try 插入新行,如果发生冲突,它会使用新行的值更新现有行的所有列.然而,在这种情况下,SEARCH不会自动处理乐观锁版本列.
要在这种情况下处理乐观锁版本列,您可以使用DoUpdate Claude显式指定要更新的列.
由于您提到您的表有多个列,并且您不想显式列出所有列,请try 下面的代码来动态生成列列表
// Define a function to get a list of columns to update excluding primary key and version
func getColumnsToUpdate(db *gorm.DB, entity interface{}) ([]string, error) {
var columnsToUpdate []string
// Retrieve table name
tableName := db.NamingStrategy.TableName("", db.Statement.Schema.Table)
// Retrieve column names
columnNames, err := db.Migrator().Columns(tableName)
if err != nil {
return nil, err
}
// Exclude primary key and version columns
for _, columnName := range columnNames {
if columnName != "ID" && columnName != "Version" {
columnsToUpdate = append(columnsToUpdate, columnName)
}
}
return columnsToUpdate, nil
}
然后更新您的查询
// Define update data
updateData := make(map[string]interface{})
for _, column := range columnsToUpdate {
updateData[column] = "updated_value" // Set your updated value here
}
// Add version update
updateData["Version"] = gorm.Expr("Version + 1")
// Apply update with OnConflict clause
dres := u.db.WithContext(context.TODO()).Clauses(clause.OnConflict{
UpdateAll: true,
}).Model(&TestEntity{}).Where("id = ?", testUpdateEntity.ID).Updates(updateData)
我希望这将有助于