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

This commit is contained in:
李龙 2021-11-29 19:57:36 +08:00
parent e1b4c066a8
commit b20fce790e
3 changed files with 16 additions and 4 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

@ -4,13 +4,12 @@ go 1.14
require (
github.com/google/uuid v1.3.0
github.com/jackc/pgtype v1.9.1 // indirect
github.com/jackc/pgx/v4 v4.14.0 // indirect
github.com/jackc/pgx/v4 v4.14.1 // indirect
github.com/jinzhu/now v1.1.3
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