Fix count with order by

This commit is contained in:
Jinzhu 2020-10-22 11:28:43 +08:00
parent 5fee5b1b24
commit 231aba53c5
2 changed files with 14 additions and 0 deletions

View File

@ -326,6 +326,15 @@ func (db *DB) Count(count *int64) (tx *DB) {
defer tx.Statement.AddClause(clause.Select{}) defer tx.Statement.AddClause(clause.Select{})
} }
if orderByClause, ok := db.Statement.Clauses["ORDER BY"]; ok {
if _, ok := db.Statement.Clauses["GROUP BY"]; !ok {
delete(db.Statement.Clauses, "ORDER BY")
defer func() {
db.Statement.Clauses["ORDER BY"] = orderByClause
}()
}
}
tx.Statement.Dest = count tx.Statement.Dest = count
tx.callbacks.Query().Execute(tx) tx.callbacks.Query().Execute(tx)
if tx.RowsAffected != 1 { if tx.RowsAffected != 1 {

View File

@ -70,6 +70,11 @@ func TestCount(t *testing.T) {
var count4 int64 var count4 int64
if err := DB.Table("users").Joins("LEFT JOIN companies on companies.name = users.name").Where("users.name = ?", user1.Name).Count(&count4).Error; err != nil || count4 != 1 { if err := DB.Table("users").Joins("LEFT JOIN companies on companies.name = users.name").Where("users.name = ?", user1.Name).Count(&count4).Error; err != nil || count4 != 1 {
t.Errorf("count with join, got error: %v, count %v", err, count4)
}
var count5 int64
if err := DB.Table("users").Where("users.name = ?", user1.Name).Order("name").Count(&count5).Error; err != nil || count5 != 1 {
t.Errorf("count with join, got error: %v, count %v", err, count) t.Errorf("count with join, got error: %v, count %v", err, count)
} }
} }