mirror of https://github.com/go-gorm/gorm.git
fix the case that using Having on Count
This commit is contained in:
parent
8b07437717
commit
26e8799a19
26
main_test.go
26
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) {
|
func BenchmarkGorm(b *testing.B) {
|
||||||
b.N = 2000
|
b.N = 2000
|
||||||
for x := 0; x < b.N; x++ {
|
for x := 0; x < b.N; x++ {
|
||||||
|
|
7
scope.go
7
scope.go
|
@ -1007,8 +1007,15 @@ func (scope *Scope) pluck(column string, value interface{}) *Scope {
|
||||||
func (scope *Scope) count(value interface{}) *Scope {
|
func (scope *Scope) count(value interface{}) *Scope {
|
||||||
if query, ok := scope.Search.selects["query"]; !ok || !countingQueryRegexp.MatchString(fmt.Sprint(query)) {
|
if query, ok := scope.Search.selects["query"]; !ok || !countingQueryRegexp.MatchString(fmt.Sprint(query)) {
|
||||||
if len(scope.Search.group) != 0 {
|
if len(scope.Search.group) != 0 {
|
||||||
|
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.Select("count(*) FROM ( SELECT count(*) as name ")
|
||||||
scope.Search.group += " ) AS count_table"
|
scope.Search.group += " ) AS count_table"
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
scope.Search.Select("count(*)")
|
scope.Search.Select("count(*)")
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue