gorm-paginate 基于 gorm 的分页插件

发布时间: 更新时间: 总字数:484 阅读时间:1m 作者: IP上海 分享 网址

gorm-paginate 基于 gorm 的分页插件,支持分页,条件搜索,排序等

介绍

Go Report Card License Go.Dev reference

English | 简体中文

GORM分页插件(program implementation for)

特性

  • 分页

    • page:当前页(默认 1)
    • size:每页记录数(默认 10)
  • 排序

    • order_by:排序字段和方向(如 created_at desc, name
  • 过滤条件

    • 格式:<field>_<operator>=<value>
      • 如:age_gt=20(where age > 20)、name_like=John%(where LIKE ‘John%’)
    • 支持的比较
      • eq 等于(默认)
      • ne 不等于
      • gt 大于
      • gte 大于等于
      • lt 小于
      • lte 小于等于
      • between 范围搜索
      • like 模糊匹配
      • notlike 非模糊匹配
      • is
      • isnot
      • in

示例

  1. 简单分页和排序
GET http://localhost:8080/users?size=10&page=0&order_by=-name,id
  • 等价的 SQL
SELECT * FROM users ORDER BY name DESC, id ASC LIMIT 10 OFFSET 0
  • JSON 响应:
{
  "page": 1,
  "size": 10,
  "order_bys": [
    {
      "field": "name",
      "direction": "desc"
    },
    {
      "field": "id",
      "direction": "asc"
    }
  ],
  "wheres": [],
  "comments": [],
  "items": [
    {
      "ID": 29,
      "CreatedAt": "2025-03-23T16:12:58.166418+08:00",
      "UpdatedAt": "2025-03-23T16:12:58.166418+08:00",
      "DeletedAt": null,
      "Name": "zxpet",
      "Age": 38,
      "Balance": 28,
      "AccountManager": "bbc"
    },
    ...
  ],
  "total": 200,
  "total_pages": 20
}
  1. 条件搜索
GET http://localhost:8080/users?size=10&page=1&age_gt=16&name_like=e%&balance_between=20,250&account_manager_in=zhangsi,lisi
  • 等价的 SQL
SELECT * FROM users WHERE age > 16 AND name LIKE "e%" and balance BETWEEN 20 AND 250 and account_manager in ("zhangsan", "lisi") LIMIT 10 OFFSET 0
  • JSON 响应:
{
  "page": 1,
  "size": 10,
  "order_bys": [],
  "wheres": [
    {
      "field": "account_manager",
      "operator": "in",
      "value": [
        "zhangsi",
        "lisi"
      ]
    },
    {
      "field": "age",
      "operator": "gt",
      "value": "16"
    },
    {
      "field": "name",
      "operator": "like",
      "value": "e%"
    }
  ],
  "comments": [
    "invalid operator: between for field: balance"
  ],
  "items": [
    {
      "ID": 113,
      "CreatedAt": "2025-03-23T17:11:45.97259+08:00",
      "UpdatedAt": "2025-03-23T17:11:45.97259+08:00",
      "DeletedAt": null,
      "Name": "etiax",
      "Age": 22,
      "Balance": 12,
      "AccountManager": "zhangsi"
    }
  ],
  "total": 200,
  "total_pages": 20
}

License

© xiexianbin, 2025~time.Now

Released under the Apache License

参考

  1. https://github.com/xiexianbin/gorm-paginate
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数