pagination

package module
v0.0.0-...-de0db93 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 23, 2023 License: Apache-2.0 Imports: 6 Imported by: 0

README

使用说明

1.引入

import "gitee.com/ostaer/gin-pagination"

2.使用中间件

app := gin.New()
paginationHandler := pagination.New(&pagination.CustomeParser{})
app.Get("/test", paginationHandler)

3.gorm引用查询数据

测试请求如middleware_test.go 110-115行

GET /test3?page=1&&size=3&&order=desc&&order_by=id&&is_child=true&&child_relation=1&&search.1.key=age&&search.1.value=5&&search.1.exactly=true&&search.2.key=email&&search.2.value=user-1,user-2&&search.2.exactly=false

查询处理如middleware_test.go 211-214行

// SELECT count(*) FROM `users`  WHERE ((`age` = "5") or ((`email` like "%user-1%") or (`email` like "%user-2%")))
DB.Model(&User{}).Scopes(pagination.PaginationScope(query, ip.Count)).Count(&count)
// SELECT * FROM `users`  WHERE ((`age` = "5") or ((`email` like "%user-1%") or (`email` like "%user-2%"))) ORDER BY id desc LIMIT 3 OFFSET 0
DB.Model(&User{}).Scopes(pagination.PaginationScope(query)).Find(&users)

4.拼接query

var query = pagination.PaginationQuery{
    PageNum: 1, PageSize: 10,
}
query.Search = append(query.Search, pagination.SearchGroup{
    SearchTerm: pagination.SearchTerm{
        Raw: &pagination.RawQuery{
            Query: "user_name = ? or nick_name = ?",
            Args: []interface{}{
                "张三", "四",
            },
        },
    },
})

自己组装gorm的Scope

var scope = func(db *gorm.DB) *gorm.DB {
	d := &pagination.PaginationQueryDB{DB: db, Query: query}
	d.ParseLimit().ParsePagination().ParseOrder()
	return d.DB
}
a.conn.Model(&model.Account{}).Scopes(scope).Where("id in ?", ids).Find(&accounts)

更多例子 参考middleware_test.go文件

文件说明

文件 说明
model.go 分页查询相关struct的定义, 如PaginationQuery
customParser.go 负责解析查询参数到PaginationQuery
resolver.go 负责解析PaginationQuery到gorm.DB Scopes
middleware.go 实现兼容gin的中间件

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ComparisionMap = map[string]string{
	"gt":     ">",
	"ge":     ">=",
	"lt":     "<",
	"le":     "<=",
	"eq":     "=",
	"ne":     "!=",
	"in":     "in",
	"not_in": "not in",
}
View Source
var PaginationQueryContextKey = "PaginationQuery"
View Source
var RequestQueryPrefix = "search"

RequestQueryPrefix 参数前缀, 用于`PaginationQuery.SearchGroup`和其他参数区分

Functions

func New

func New(pagination Pagination) gin.HandlerFunc

PaginationParser 兼容gin中间件 从`gin.Context`中解析`PaginationQuery` url例子: page=1&&size=10&&search.1.key=age&&search.1.value=20&&search.2.key=gender&&search.2.value=0&&orderfield=age&&orderby=desc&&search.1.exactly=true&&search.2.exactly=false

func PaginationScope

func PaginationScope(query *PaginationQuery, options ...Option) func(db *gorm.DB) *gorm.DB

PaginationScope 解析PaginationQuery到gorm.DB Scopes 示例:

Query := &PaginationQuery{}

查询例子:

var result []yourModel
DB.Scopes(PaginationScope(Query)).Find(&result)

查询总数示例:

var c int
DB.Scopes(PaginationScope(Query, Count)).Count(&c)

Types

type CustomeParser

type CustomeParser struct{}

func (*CustomeParser) Parser

Parser 建议自己实现分页解析接口 可以自定义解析GET/POST参数,此处以GET为例子

type Option

type Option int

Options自定义的选项,用户区分PaginationScope不同的组合查询条件

const (
	// Count Option=0的时候,标志返回查询总条数的语句
	Count Option = iota
)

type Pagination

type Pagination interface {
	Parser(c *gin.Context) *PaginationQuery
}

Pagination 实现这个接口,把前端传过来的参数解析成需要的`PaginationQuery` 接口的`Parse`可以自定义足够复杂,相对应前端需要传的参数越多,该方法的解析越复杂

type PaginationQuery

type PaginationQuery struct {
	PageSize int
	PageNum  int
	// OrderBy 小写的字段名称
	OrderBy string
	// Order 默认是'desc', 可选的: 'desc', 'asc'
	Order string
	// Limit 当指定pagesize时, limit参数是无效的
	Limit int
	// SearchGroup 其他搜索条件, 各个查询组之间是AND关系
	Search []SearchGroup
	// Scope 仅在复杂查询时候使用(包含多个表查询的时候)
	// 一般来说, Scope是表的名字, 用以表明哪个表用作复杂的匹配
	// 例如: join多个表有相同的字段名的时候
	Scope string
}

PaginationQuery 分页查询

type PaginationQueryDB

type PaginationQueryDB struct {
	DB    *gorm.DB
	Query *PaginationQuery
}

PaginationQueryDB 包含gorm.DB的结构体

func (*PaginationQueryDB) ParseLimit

func (d *PaginationQueryDB) ParseLimit() *PaginationQueryDB

ParseLimit 解析Limit

func (*PaginationQueryDB) ParseOrder

func (d *PaginationQueryDB) ParseOrder() *PaginationQueryDB

ParseOrder 解析排序

func (*PaginationQueryDB) ParsePagination

func (d *PaginationQueryDB) ParsePagination() *PaginationQueryDB

ParsePagination 解析分页条件

func (*PaginationQueryDB) ParseQuery

func (d *PaginationQueryDB) ParseQuery() *PaginationQueryDB

ParseQuery 解析查询条件

type RawQuery

type RawQuery struct {
	Query interface{}
	Args  []interface{}
}

type SearchGroup

type SearchGroup struct {
	SearchTerm
	// isChildQuery 是否包含子查询
	IsChildQuery bool
	// ChildSearch子查询,嵌套搜索, 仅仅当isChildQuery是true的时候有效
	ChildSearch []SearchTerm
	// ChildRelation, 子查询多个条件之间的关系,仅仅当isChildQuery是true的时候有效,默认值是AND
	ChildRelation SearchRelation
}

SearchGroup 查询组定义 有子查询(ChildSearch) IsChildQuery=true的情况下,会忽略该Search里的查询直接查询子查询

type SearchRelation

type SearchRelation int

SearchRelation 搜索查询添加 And或者Or

const (
	ChildSearchAnd SearchRelation = iota
	ChildSearchOr
)

type SearchTerm

type SearchTerm struct {
	// key是搜索的键
	// value是搜索的值,可以是value1,value2, 多个值的时候将会被翻译成 "or" 的关系
	// scope和`PaginationQuery.Scope`相似
	Key, Value, Scope string
	// Comparision key和value之间的关系, 默认eq即等于
	// 参考ComparisionMap
	Comparision string
	// Exactly 精确匹配/模糊配置
	Exactly bool
	// 支持裸写查询SQL
	Raw *RawQuery
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL