From b90f11223971b6d31fffc4efad321ca5156c9caa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E9=BE=99?= Date: Thu, 25 Nov 2021 12:57:16 +0800 Subject: [PATCH] fix: count() when use `group by` and only find one record --- finisher_api.go | 5 +++++ tests/count_test.go | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/finisher_api.go b/finisher_api.go index 920ea739..78f764b8 100644 --- a/finisher_api.go +++ b/finisher_api.go @@ -422,6 +422,11 @@ func (db *DB) Count(count *int64) (tx *DB) { if tx.RowsAffected != 1 { *count = tx.RowsAffected } + + if _, ok := db.Statement.Clauses["GROUP BY"]; ok && tx.RowsAffected == 1 { + *count = tx.RowsAffected + } + return } diff --git a/tests/count_test.go b/tests/count_test.go index de06d0eb..94c66663 100644 --- a/tests/count_test.go +++ b/tests/count_test.go @@ -134,4 +134,14 @@ 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) + } }