Skip to content

Commit

Permalink
fix the case that using Having on Count
Browse files Browse the repository at this point in the history
  • Loading branch information
xwjdsh committed Mar 11, 2019
1 parent 8b07437 commit 26e8799
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
26 changes: 26 additions & 0 deletions main_test.go
Expand Up @@ -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++ {
Expand Down
11 changes: 9 additions & 2 deletions scope.go
Expand Up @@ -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(*)")
}
Expand Down

0 comments on commit 26e8799

Please sign in to comment.