From 058ce7a4d4eb7e146a2ab98cd420aa6dcad21bbc Mon Sep 17 00:00:00 2001 From: hulutech-web Date: Mon, 21 Oct 2024 23:30:13 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=97=B6=E9=97=B4=E8=8C=83?= =?UTF-8?q?=E5=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- paginator.go | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3acbd04..a948791 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ func (r *MaterialController) Index(ctx http.Context) http.Response { ##### 解释二:查询参数:order仅支持asc,desc默认采用asc,sort表示需要查询的列,order参数和sort参数需要同时出现 ##### 解释三:前端,可以配合vue组件,https://vxetable.cn,使用效率更高 ```go -// Index 用户分页查询,支持搜索,路由参数?name=xxx&pageSize=1¤tPage=1&sort=xxx&order=xxx,等其他任意的查询参数 +// Index 用户分页查询,支持时间,支持搜索,路由参数?name=xxx&pageSize=1¤tPage=1&sort=xxx&order=xxx&created_at[]=xxx&created_at[]=xxx,等其他任意的查询参数 // @Summary 用户分页查询 // @Description 用户分页查询 // @Tags 用户分页查询 diff --git a/paginator.go b/paginator.go index fea77d7..32a3d9f 100644 --- a/paginator.go +++ b/paginator.go @@ -8,6 +8,7 @@ import ( "gorm.io/gorm" "math" "strconv" + "strings" ) type Meta struct { @@ -41,16 +42,39 @@ func (h *HttpResult) SearchByParams(params map[string]string, conditionMap map[s // 再处理url查询 h.Query = func(q orm.Query) orm.Query { + //处理日期时间 // 先处理过滤条件 for key, val := range conditionMap { q = q.Where(key+" = ?", val).(orm.Query) } + timeKey := []string{} + ranges := []string{} for key, value := range params { + //如果key包含了[]符号 + if value == "" || key == "pageSize" || key == "total" || key == "currentPage" || key == "sort" || key == "order" { continue } else { q = q.Where(gorm.Expr(key+" LIKE ?", "%"+value+"%")) } + //则表示是日期时间范围 + /** + created_at[]: 2024-10-21 00:00:00 + created_at[]: 2024-10-21 23:59:59 + */ + if strings.Contains(key, "[]") { + key = strings.Replace(key, "[]", "", -1) + if value == "" { + continue + } + //第一是开始时间,第二个是结束时间 + ranges = append(ranges, value) + timeKey = append(timeKey, key) + } + } + if len(ranges) == 2 && len(timeKey) == 2 && timeKey[0] == timeKey[1] { + q = q.Where(timeKey[0]+" BETWEEN ? AND ?", ranges[0], ranges[1]) + ranges = []string{} } return q }(query)