From 33601dc72f4abf86ce68cbb663f7f5c898bee0a3 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 30 Mar 2021 18:28:09 +0800 Subject: [PATCH] Support Having w/o Group --- clause/group_by.go | 6 ++++++ tests/group_by_test.go | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/clause/group_by.go b/clause/group_by.go index 88231916..84242fb8 100644 --- a/clause/group_by.go +++ b/clause/group_by.go @@ -39,4 +39,10 @@ func (groupBy GroupBy) MergeClause(clause *Clause) { groupBy.Having = append(copiedHaving, groupBy.Having...) } clause.Expression = groupBy + + if len(groupBy.Columns) == 0 { + clause.Name = "" + } else { + clause.Name = groupBy.Name() + } } diff --git a/tests/group_by_test.go b/tests/group_by_test.go index 7e41e94a..96dfc547 100644 --- a/tests/group_by_test.go +++ b/tests/group_by_test.go @@ -96,4 +96,14 @@ func TestGroupBy(t *testing.T) { if name != "groupby" || active != true || total != 40 { t.Errorf("group by two columns, name %v, age %v, active: %v", name, total, active) } + + if DB.Dialector.Name() == "mysql" { + if err := DB.Model(&User{}).Select("name, age as total").Where("name LIKE ?", "groupby%").Having("total > ?", 300).Scan(&result).Error; err != nil { + t.Errorf("no error should happen, but got %v", err) + } + + if result.Name != "groupby1" || result.Total != 330 { + t.Errorf("name should be groupby, total should be 660, but got %+v", result) + } + } }