Skip to content

Commit fce92be

Browse files
committed
feat: add group
1 parent dfaa965 commit fce92be

File tree

3 files changed

+23
-3
lines changed

3 files changed

+23
-3
lines changed

gormplus/mapper.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,12 @@ func SelectOne[T any](q *Query[T]) (*gorm.DB, T) {
8181

8282
func SelectList[T any](q *Query[T]) (*gorm.DB, []T) {
8383
var results []T
84-
resultDb := GormDb.Order(q.OrderBuilder.String()).Select(q.Columns).Where(q.QueryBuilder.String(), q.Args...).Find(&results)
84+
resultDb := GormDb.Select(q.Columns).Where(q.QueryBuilder.String(), q.Args...).
85+
Order(q.OrderBuilder.String())
86+
if q.GroupBuilder.Len() > 0 {
87+
resultDb.Group(q.GroupBuilder.String())
88+
}
89+
resultDb.Find(&results)
8590
return resultDb, results
8691
}
8792

gormplus/mapper_test.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package gormplus
22

33
import (
4+
"encoding/json"
45
"fmt"
56
"gorm.io/driver/mysql"
67
"gorm.io/gorm"
@@ -116,10 +117,13 @@ func TestSelectOne(t *testing.T) {
116117

117118
func TestSelectList(t *testing.T) {
118119
q := Query[Test1]{}
119-
q.OrderByDesc("price").OrderByAsc("code")
120+
q.Group("price", "code")
120121
db, result := SelectList(&q)
121122
fmt.Println(db.RowsAffected)
122-
fmt.Println(result)
123+
for _, v := range result {
124+
marshal, _ := json.Marshal(v)
125+
fmt.Println(string(marshal))
126+
}
123127
}
124128

125129
func TestSelectCount(t *testing.T) {

gormplus/query.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
type Query[T any] struct {
1010
Columns []string
1111
OrderBuilder strings.Builder
12+
GroupBuilder strings.Builder
1213
QueryBuilder strings.Builder
1314
Args []any
1415
LastCond string
@@ -102,6 +103,16 @@ func (q *Query[T]) OrderByAsc(columns ...string) *Query[T] {
102103
return q
103104
}
104105

106+
func (q *Query[T]) Group(columns ...string) *Query[T] {
107+
for _, v := range columns {
108+
if q.GroupBuilder.Len() > 0 {
109+
q.GroupBuilder.WriteString(constants.COMMA)
110+
}
111+
q.GroupBuilder.WriteString(v)
112+
}
113+
return q
114+
}
115+
105116
func (q *Query[T]) addCond(column string, val any, condType string) {
106117
if q.LastCond != constants.And && q.LastCond != constants.Or && q.QueryBuilder.Len() > 0 {
107118
q.QueryBuilder.WriteString(constants.And)

0 commit comments

Comments
 (0)