fix: FirstOrCreate RowsAffected (#5250)

This commit is contained in:
Cr 2022-04-13 15:52:07 +08:00 committed by GitHub
parent 6aa6d37fc4
commit a65912c588
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 0 deletions

View File

@ -326,6 +326,9 @@ func (db *DB) FirstOrCreate(dest interface{}, conds ...interface{}) (tx *DB) {
}
return tx.Model(dest).Updates(assigns)
} else {
// can not use Find RowsAffected
tx.RowsAffected = 0
}
}
return tx

View File

@ -526,3 +526,17 @@ func TestCreateNilPointer(t *testing.T) {
t.Fatalf("it is not ErrInvalidValue")
}
}
func TestFirstOrCreateRowsAffected(t *testing.T) {
user := User{Name: "TestFirstOrCreateRowsAffected"}
res := DB.FirstOrCreate(&user, "name = ?", user.Name)
if res.Error != nil || res.RowsAffected != 1 {
t.Fatalf("first or create rows affect err:%v rows:%d", res.Error, res.RowsAffected)
}
res = DB.FirstOrCreate(&user, "name = ?", user.Name)
if res.Error != nil || res.RowsAffected != 0 {
t.Fatalf("first or create rows affect err:%v rows:%d", res.Error, res.RowsAffected)
}
}