From 26e8799a192569dcc22efd1d43f96a0bb1bafe81 Mon Sep 17 00:00:00 2001
From: Wendell Sun <iwendellsun@gmail.com>
Date: Mon, 11 Mar 2019 19:56:03 +0800
Subject: [PATCH] fix the case that using Having on Count

---
 main_test.go | 26 ++++++++++++++++++++++++++
 scope.go     | 11 +++++++++--
 2 files changed, 35 insertions(+), 2 deletions(-)

diff --git a/main_test.go b/main_test.go
index 94d2fa39..ac40c32b 100644
--- a/main_test.go
+++ b/main_test.go
@@ -1059,6 +1059,32 @@ func TestBlockGlobalUpdate(t *testing.T) {
 	}
 }
 
+func TestCountWithHaving(t *testing.T) {
+	db := DB.New()
+	db.Delete(User{})
+	defer db.Delete(User{})
+
+	DB.Create(getPreparedUser("user1", "pluck_user"))
+	DB.Create(getPreparedUser("user2", "pluck_user"))
+	user3:=getPreparedUser("user3", "pluck_user")
+	user3.Languages=[]Language{}
+	DB.Create(user3)
+
+	var count int
+	err:=db.Model(User{}).Select("users.id").
+		Joins("LEFT JOIN user_languages ON user_languages.user_id = users.id").
+		Joins("LEFT JOIN languages ON user_languages.language_id = languages.id").
+		Group("users.id").Having("COUNT(languages.id) > 1").Count(&count).Error
+
+	if err != nil {
+		t.Error("Unexpected error on query count with having")
+	}
+
+	if count!=2{
+		t.Error("Unexpected result on query count with having")
+	}
+}
+
 func BenchmarkGorm(b *testing.B) {
 	b.N = 2000
 	for x := 0; x < b.N; x++ {
diff --git a/scope.go b/scope.go
index 90e16782..7fa64b19 100644
--- a/scope.go
+++ b/scope.go
@@ -1007,8 +1007,15 @@ func (scope *Scope) pluck(column string, value interface{}) *Scope {
 func (scope *Scope) count(value interface{}) *Scope {
 	if query, ok := scope.Search.selects["query"]; !ok || !countingQueryRegexp.MatchString(fmt.Sprint(query)) {
 		if len(scope.Search.group) != 0 {
-			scope.Search.Select("count(*) FROM ( SELECT count(*) as name ")
-			scope.Search.group += " ) AS count_table"
+			if len(scope.Search.havingConditions) != 0 {
+				scope.prepareQuerySQL()
+				scope.Search = &search{}
+				scope.Search.Select("count(*)")
+				scope.Search.Table(fmt.Sprintf("( %s ) AS count_table", scope.SQL))
+			} else {
+				scope.Search.Select("count(*) FROM ( SELECT count(*) as name ")
+				scope.Search.group += " ) AS count_table"
+			}
 		} else {
 			scope.Search.Select("count(*)")
 		}