Skip to content

Commit

Permalink
fix: count() when use group by and only find one record (go-gorm#4885)
Browse files Browse the repository at this point in the history
Co-authored-by: 李龙 <[email protected]>
  • Loading branch information
kinggo and li-jin-gou authored Nov 29, 2021
1 parent 27e2753 commit d8a710c
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
4 changes: 3 additions & 1 deletion finisher_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -419,9 +419,11 @@ func (db *DB) Count(count *int64) (tx *DB) {

tx.Statement.Dest = count
tx = tx.callbacks.Query().Execute(tx)
if tx.RowsAffected != 1 {

if _, ok := db.Statement.Clauses["GROUP BY"]; ok || tx.RowsAffected != 1 {
*count = tx.RowsAffected
}

return
}

Expand Down
11 changes: 11 additions & 0 deletions tests/count_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,4 +134,15 @@ func TestCount(t *testing.T) {
t.Fatalf("Count should be 3, but got count: %v err %v", count10, err)
}

var count11 int64
sameUsers := make([]*User, 0)
for i := 0; i < 3; i++ {
sameUsers = append(sameUsers, GetUser("count-4", Config{}))
}
DB.Create(sameUsers)

if err := DB.Model(&User{}).Where("name = ?", "count-4").Group("name").Count(&count11).Error; err != nil || count11 != 1 {
t.Fatalf("Count should be 3, but got count: %v err %v", count11, err)
}

}
2 changes: 1 addition & 1 deletion tests/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ require (
github.com/lib/pq v1.10.4
golang.org/x/crypto v0.0.0-20211117183948-ae814b36b871 // indirect
gorm.io/driver/mysql v1.2.0
gorm.io/driver/postgres v1.2.2
gorm.io/driver/postgres v1.2.3
gorm.io/driver/sqlite v1.2.6
gorm.io/driver/sqlserver v1.2.1
gorm.io/gorm v1.22.3
Expand Down

0 comments on commit d8a710c

Please sign in to comment.