From d8a710cba23367a0e9adbaaf751c60041a1f7df6 Mon Sep 17 00:00:00 2001 From: kinggo <30891428+longlihale@users.noreply.github.com> Date: Mon, 29 Nov 2021 20:14:23 +0800 Subject: [PATCH] fix: count() when use group by and only find one record (#4885) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 李龙 --- finisher_api.go | 4 +++- tests/count_test.go | 11 +++++++++++ tests/go.mod | 2 +- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/finisher_api.go b/finisher_api.go index 633a7fa06..b3bdedc80 100644 --- a/finisher_api.go +++ b/finisher_api.go @@ -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 } diff --git a/tests/count_test.go b/tests/count_test.go index de06d0eb7..7cae890b5 100644 --- a/tests/count_test.go +++ b/tests/count_test.go @@ -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) + } + } diff --git a/tests/go.mod b/tests/go.mod index 4fddb6628..6315c7f1a 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -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