Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions contrib/drivers/mysql/mysql_z_unit_feature_model_join_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,29 @@ func Test_Model_FieldsPrefix(t *testing.T) {
t.Assert(r[0]["nickname"], "name_1")
})
}

func Test_Model_Group_WithJoin(t *testing.T) {
var (
table1 = gtime.TimestampNanoStr() + "_user"
table2 = gtime.TimestampNanoStr() + "_user_detail"
)
createInitTable(table1)
defer dropTable(table1)
createInitTable(table2)
defer dropTable(table2)

gtest.C(t, func(t *gtest.T) {
// This test verifies that Group works with JOINs and generates qualified column names
// to avoid "Column 'id' in group statement is ambiguous" errors
r, err := db.Model(table1+" u").
Fields("u.id", "u.name", "COUNT(*) as count").
LeftJoin(table2+" ud", "u.id = ud.id").
Where("u.id", g.Slice{1, 2}).
Group("u.id").
Order("u.id asc").All()
t.AssertNil(err)
t.Assert(len(r), 2)
t.Assert(r[0]["id"], "1")
t.Assert(r[1]["id"], "2")
})
}
40 changes: 33 additions & 7 deletions database/gdb/gdb_model_order_group.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
package gdb

import (
"strings"
"fmt"

"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
Expand Down Expand Up @@ -78,18 +78,44 @@ func (m *Model) OrderRandom() *Model {
}

// Group sets the "GROUP BY" statement for the model.
func (m *Model) Group(groupBy ...string) *Model {
func (m *Model) Group(groupBy ...any) *Model {
if len(groupBy) == 0 {
return m
}
var (
core = m.db.GetCore()
model = m.getModel()
core = m.db.GetCore()
model = m.getModel()
autoPrefix = ""
)

if model.groupBy != "" {
model.groupBy += ","
// Check if we need to auto-prefix columns when there are JOINs
if gstr.Contains(m.tables, " JOIN ") {
autoPrefix = m.QuoteWord(
core.guessPrimaryTableName(m.tablesInit),
)
}

for _, v := range groupBy {
if model.groupBy != "" {
model.groupBy += ","
}
switch v.(type) {
case Raw, *Raw:
model.groupBy += gconv.String(v)
default:
groupByStr := gconv.String(v)
if gstr.Contains(groupByStr, ".") {
// Already qualified (e.g., "table.column")
model.groupBy += core.QuoteString(groupByStr)
} else {
// Need to qualify with table prefix if there are joins
if autoPrefix != "" {
model.groupBy += fmt.Sprintf("%s.%s", autoPrefix, core.QuoteWord(groupByStr))
} else {
model.groupBy += core.QuoteWord(groupByStr)
}
}
}
}
model.groupBy += core.QuoteString(strings.Join(groupBy, ","))
return model
}
Loading