fix: diff schema update assign value (#6096)

This commit is contained in:
Cr 2023-03-10 17:04:54 +08:00 committed by GitHub
parent 707d70a542
commit b62192456f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 1 deletions

View File

@ -245,11 +245,13 @@ func ConvertToAssignments(stmt *gorm.Statement) (set clause.Set) {
}
default:
updatingSchema := stmt.Schema
var isDiffSchema bool
if !updatingValue.CanAddr() || stmt.Dest != stmt.Model {
// different schema
updatingStmt := &gorm.Statement{DB: stmt.DB}
if err := updatingStmt.Parse(stmt.Dest); err == nil {
updatingSchema = updatingStmt.Schema
isDiffSchema = true
}
}
@ -276,7 +278,13 @@ func ConvertToAssignments(stmt *gorm.Statement) (set clause.Set) {
if (ok || !isZero) && field.Updatable {
set = append(set, clause.Assignment{Column: clause.Column{Name: field.DBName}, Value: value})
assignValue(field, value)
assignField := field
if isDiffSchema {
if originField := stmt.Schema.LookUpField(dbName); originField != nil {
assignField = originField
}
}
assignValue(assignField, value)
}
}
} else {

View File

@ -773,3 +773,16 @@ func TestUpdateReturning(t *testing.T) {
t.Errorf("failed to return updated age column")
}
}
func TestUpdateWithDiffSchema(t *testing.T) {
user := GetUser("update-diff-schema-1", Config{})
DB.Create(&user)
type UserTemp struct {
Name string
}
err := DB.Model(&user).Updates(&UserTemp{Name: "update-diff-schema-2"}).Error
AssertEqual(t, err, nil)
AssertEqual(t, "update-diff-schema-2", user.Name)
}