fix: count() when use group by and only find one record (#4885)

Co-authored-by: 李龙 <lilong.21@bytedance.com>
This commit is contained in:
kinggo 2021-11-29 20:14:23 +08:00 committed by GitHub
parent 27e2753c9d
commit d8a710cba2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 15 additions and 2 deletions

View File

@ -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
}

View File

@ -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)
}
}

View File

@ -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