From a9cdf1dc7f9920a015a8e4e9dab046c4f466f5a0 Mon Sep 17 00:00:00 2001 From: kiwih Date: Wed, 22 Jul 2015 15:00:20 +1200 Subject: [PATCH] Add basic support for multiple HAVING clauses. All clauses will be ANDed together. --- scope_private.go | 18 ++++++++++++++++-- search.go | 38 +++++++++++++++++++------------------- 2 files changed, 35 insertions(+), 21 deletions(-) diff --git a/scope_private.go b/scope_private.go index edd0dbe9..f8620f34 100644 --- a/scope_private.go +++ b/scope_private.go @@ -265,10 +265,24 @@ func (scope *Scope) groupSql() string { } func (scope *Scope) havingSql() string { - if scope.Search.havingCondition == nil { + if scope.Search.havingConditions == nil { return "" } - return " HAVING " + scope.buildWhereCondition(scope.Search.havingCondition) + + var andConditions []string + + for _, clause := range scope.Search.havingConditions { + if sql := scope.buildWhereCondition(clause); sql != "" { + andConditions = append(andConditions, sql) + } + } + + combinedSql := strings.Join(andConditions, " AND ") + if len(combinedSql) == 0 { + return "" + } + + return " HAVING " + combinedSql } func (scope *Scope) joinsSql() string { diff --git a/search.go b/search.go index 9411af43..130415ef 100644 --- a/search.go +++ b/search.go @@ -3,24 +3,24 @@ package gorm import "fmt" type search struct { - db *DB - whereConditions []map[string]interface{} - orConditions []map[string]interface{} - notConditions []map[string]interface{} - havingCondition map[string]interface{} - initAttrs []interface{} - assignAttrs []interface{} - selects map[string]interface{} - omits []string - orders []string - joins string - preload []searchPreload - offset string - limit string - group string - tableName string - raw bool - Unscoped bool + db *DB + whereConditions []map[string]interface{} + orConditions []map[string]interface{} + notConditions []map[string]interface{} + havingConditions []map[string]interface{} + initAttrs []interface{} + assignAttrs []interface{} + selects map[string]interface{} + omits []string + orders []string + joins string + preload []searchPreload + offset string + limit string + group string + tableName string + raw bool + Unscoped bool } type searchPreload struct { @@ -93,7 +93,7 @@ func (s *search) Group(query string) *search { } func (s *search) Having(query string, values ...interface{}) *search { - s.havingCondition = map[string]interface{}{"query": query, "args": values} + s.havingConditions = append(s.havingConditions, map[string]interface{}{"query": query, "args": values}) return s }