Fix Save with specified table, close #3396

This commit is contained in:
Jinzhu 2020-09-06 12:22:05 +08:00
parent 6e38a2c2d5
commit 05794298bd
2 changed files with 24 additions and 1 deletions

View File

@ -51,7 +51,8 @@ func (db *DB) Save(value interface{}) (tx *DB) {
tx.callbacks.Update().Execute(tx) tx.callbacks.Update().Execute(tx)
if tx.Error == nil && tx.RowsAffected == 0 && !tx.DryRun && !selectedUpdate { if tx.Error == nil && tx.RowsAffected == 0 && !tx.DryRun && !selectedUpdate {
if err := tx.Session(&Session{}).First(value).Error; errors.Is(err, ErrRecordNotFound) { result := reflect.New(tx.Statement.Schema.ModelType).Interface()
if err := tx.Session(&Session{WithConditions: true}).First(result).Error; errors.Is(err, ErrRecordNotFound) {
return tx.Create(value) return tx.Create(value)
} }
} }

View File

@ -629,4 +629,26 @@ func TestSaveWithPrimaryValue(t *testing.T) {
var result2 Language var result2 Language
DB.First(&result2, "code = ?", "save") DB.First(&result2, "code = ?", "save")
AssertEqual(t, result2, lang) AssertEqual(t, result2, lang)
DB.Table("langs").Migrator().DropTable(&Language{})
DB.Table("langs").AutoMigrate(&Language{})
if err := DB.Table("langs").Save(&lang).Error; err != nil {
t.Errorf("no error should happen when creating data, but got %v", err)
}
var result3 Language
if err := DB.Table("langs").First(&result3, "code = ?", lang.Code).Error; err != nil || result3.Name != lang.Name {
t.Errorf("failed to find created record, got error: %v, result: %+v", err, result3)
}
lang.Name += "name2"
if err := DB.Table("langs").Save(&lang).Error; err != nil {
t.Errorf("no error should happen when creating data, but got %v", err)
}
var result4 Language
if err := DB.Table("langs").First(&result4, "code = ?", lang.Code).Error; err != nil || result4.Name != lang.Name {
t.Errorf("failed to find created record, got error: %v, result: %+v", err, result4)
}
} }