Refactoring, adding Having Subquery support, allowing db.T for tablenames

This commit is contained in:
ManReinsp 2017-07-28 11:05:29 +02:00
parent 84847fdd47
commit 45370c3332
3 changed files with 26 additions and 3 deletions

View File

@ -226,7 +226,7 @@ func (s *DB) Group(query string) *DB {
}
// Having specify HAVING conditions for GROUP BY
func (s *DB) Having(query string, values ...interface{}) *DB {
func (s *DB) Having(query interface{}, values ...interface{}) *DB {
return s.clone().search.Having(query, values...).db
}

View File

@ -633,6 +633,25 @@ func TestQueryBuilderSubselectInWhere(t *testing.T) {
}
}
func TestQueryBuilderSubselectInHaving(t *testing.T) {
user := User{Name: "user1", Email: "root@user1.com", Age: 64}
DB.Save(&user)
user = User{Name: "user2", Email: "root@user2.com", Age: 128}
DB.Save(&user)
user = User{Name: "user3", Email: "root@user1.com", Age: 64}
DB.Save(&user)
user = User{Name: "user4", Email: "root@user2.com", Age: 128}
DB.Save(&user)
var users []User
DB.Debug().Select("AVG(age) as avgage").Group("email").Having("avgage > ?", DB.
Select("AVG(age)").Table("users").Subquery()).Find(&users)
if len(users) != 1 {
t.Errorf("One user group should be found, instead found %d", len(users))
}
}
func DialectHasTzSupport() bool {
// NB: mssql and FoundationDB do not support time zones.
if dialect := os.Getenv("GORM_DIALECT"); dialect == "mssql" || dialect == "foundation" {

View File

@ -104,8 +104,12 @@ func (s *search) Group(query string) *search {
return s
}
func (s *search) Having(query string, values ...interface{}) *search {
func (s *search) Having(query interface{}, values ...interface{}) *search {
if val, ok := query.(*expr); ok {
s.havingConditions = append(s.havingConditions, map[string]interface{}{"query": val.expr, "args": val.args})
} else {
s.havingConditions = append(s.havingConditions, map[string]interface{}{"query": query, "args": values})
}
return s
}