Fix RowsAffected not returned for FirstOrCreate

This commit is contained in:
Jinzhu 2016-10-21 11:30:17 +08:00
parent a667ab8427
commit 89b7cbe89c
2 changed files with 11 additions and 5 deletions

View File

@ -330,13 +330,13 @@ func (s *DB) FirstOrInit(out interface{}, where ...interface{}) *DB {
// https://jinzhu.github.io/gorm/curd.html#firstorcreate
func (s *DB) FirstOrCreate(out interface{}, where ...interface{}) *DB {
c := s.clone()
if result := c.First(out, where...); result.Error != nil {
if result := s.First(out, where...); result.Error != nil {
if !result.RecordNotFound() {
return result
}
c.AddError(c.NewScope(out).inlineCondition(where...).initialize().callCallbacks(c.parent.callbacks.creates).db.Error)
return c.NewScope(out).inlineCondition(where...).initialize().callCallbacks(c.parent.callbacks.creates).db
} else if len(c.search.assignAttrs) > 0 {
c.AddError(c.NewScope(out).InstanceSet("gorm:update_interface", c.search.assignAttrs).callCallbacks(c.parent.callbacks.updates).db.Error)
return c.NewScope(out).InstanceSet("gorm:update_interface", c.search.assignAttrs).callCallbacks(c.parent.callbacks.updates).db
}
return c
}

View File

@ -315,8 +315,14 @@ func TestNullValuesWithFirstOrCreate(t *testing.T) {
}
var nv2 NullValue
if err := DB.Where(nv1).FirstOrCreate(&nv2).Error; err != nil {
t.Errorf("Should not raise any error, but got %v", err)
result := DB.Where(nv1).FirstOrCreate(&nv2)
if result.RowsAffected != 1 {
t.Errorf("RowsAffected should be 1 after create some record")
}
if result.Error != nil {
t.Errorf("Should not raise any error, but got %v", result.Error)
}
if nv2.Name.String != "first_or_create" || nv2.Gender.String != "M" {