From 231aba53c58fcb9ca0e3a70375eba88b337ad4cc Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 22 Oct 2020 11:28:43 +0800 Subject: [PATCH] Fix count with order by --- finisher_api.go | 9 +++++++++ tests/count_test.go | 5 +++++ 2 files changed, 14 insertions(+) diff --git a/finisher_api.go b/finisher_api.go index 2951fdef..30616284 100644 --- a/finisher_api.go +++ b/finisher_api.go @@ -326,6 +326,15 @@ func (db *DB) Count(count *int64) (tx *DB) { 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.callbacks.Query().Execute(tx) if tx.RowsAffected != 1 { diff --git a/tests/count_test.go b/tests/count_test.go index 0d348227..41bad71d 100644 --- a/tests/count_test.go +++ b/tests/count_test.go @@ -70,6 +70,11 @@ func TestCount(t *testing.T) { 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 { + 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) } }