专业编程教程与实战项目分享平台

网站首页 > 技术文章 正文

GO语言札记-分页技术实现

ins518 2024-09-21 00:35:22 技术文章 17 ℃ 0 评论

前沿

在做通用后台时,尝尝会用到分页技术,下面是常用的分页实现:

代码实现

type PageOptions struct {
	TableName           string //表名  -----------------[必填]
	Conditions          string //条件
	CurrentPage         int    //当前页 ,默认1 每次分页,必须在前台设置新的页数,不设置始终默认1.在控制器中使用方式:cp, _ := this.GetInt("pno")   po.CurrentPage = int(cp)
	PageSize            int    //页面大小,默认20
	LinkItemCount       int    //生成A标签的个数 默认10个
	Href                string //A标签的链接地址  ---------[不需要设置]
	ParamName           string //参数名称  默认是pno
	FirstPageText       string //首页文字  默认"首页"
	LastPageText        string //尾页文字  默认"尾页"
	PrePageText         string //上一页文字 默认"上一页"
	NextPageText        string //下一页文字 默认"下一页"
	EnableFirstLastLink bool   //是否启用首尾连接 默认false 建议开启
	EnablePreNexLink    bool   //是否启用上一页,下一页连接 默认false 建议开启
	TotalPages          int
}

/**
 * 分页函数,适用任何表
 * 返回 总记录条数,总页数,以及当前请求的数据RawSeter,调用中需要"rs.QueryRows(&tblog)"就行了  --tblog是一个Tb_log对象
 * 参数:表名,当前页数,页面大小,条件(查询条件,格式为 " and name='zhifeiya' and age=12 ")
 */
func GetPagesInfo(tableName string, currentpage int, pagesize int, conditions string) (int, int, orm.RawSeter) {
	if currentpage <= 1 {
		currentpage = 1
	}
	if pagesize == 0 {
		pagesize = 20
	}
	var rs orm.RawSeter
	var o = orm.NewOrm()
	var totalItem, totalpages int = 0, 0                                                                //总条数,总页数
	_ = o.Raw("SELECT count(*) FROM " + tableName + "  where 1 > 0 " + conditions).QueryRow(&totalItem) //获取总条数
	if totalItem <= pagesize {
		totalpages = 1
	} else if totalItem > pagesize {
		temp := totalItem / pagesize
		if (totalItem % pagesize) != 0 {
			temp = temp + 1
		}
		totalpages = temp
	}
	rs = o.Raw("select *  from  " + tableName + "  where 1 > 0 " + conditions + " LIMIT " + strconv.Itoa((currentpage-1)*pagesize) + "," + strconv.Itoa(pagesize))
	return totalItem, totalpages, rs
}

使用过程

// --------------------------具体业务--------------------------------------------
	var maps []orm.Params
	//userModel := models.User{}
	currentpage := sceneForm.CurrentPage
	pagesize := 1000 //sceneForm.PageSize
	keyword := sceneForm.KeyWord
	mysqlstr := ""
	if keyword !="" {
		mysqlstr = "  and ( a1.title like '%"+keyword+"%'" + " or a1.create_name like '%"+keyword+"%'" + " or a1.id like '%"+keyword+"%'" + " or a1.scene_id like '%"+keyword+"%')"
	}
	totalItem,totalpages,rs := utils.GetPagesInfo("tb_scene a1",currentpage,pagesize,mysqlstr)
	_, _ = rs.Values(&maps)
......

结果展示

{
  "code": 0,
  "msg": "成功",
  "data": [
    {
    }
  ],
  "serverTime": "2020-11-10 14:36:07",
  "totalPage": 1,
  "PageSize": 1000,
  "currentPage": 0,
  "total": 23
}

更多关注

https://blog.csdn.net/BaiHuaXiu123

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表