mirror of https://github.com/go-gorm/gorm.git
fix: diff schema update assign value (#6096)
This commit is contained in:
parent
707d70a542
commit
b62192456f
|
@ -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 {
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue