page_utils.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package utils
  2. import (
  3. "fmt"
  4. "git.i2edu.net/i2/i2-bill-api/internal/types"
  5. "github.com/xormplus/xorm"
  6. "html/template"
  7. )
  8. // 分页查询
  9. func PageSearch(db *xorm.Engine, controllername string, apiname string, tableName string, params map[string]interface{}) (*types.PageResult, error) {
  10. page, _ := params["page"].(int)
  11. rows, _ := params["rows"].(int)
  12. if page == 0 {
  13. page = 1
  14. }
  15. if rows == 0 {
  16. rows = 10
  17. params["rows"] = rows
  18. }
  19. offset := (page - 1) * rows
  20. params["offset"] = offset
  21. params["ge"] = template.HTML(">=")
  22. params["le"] = template.HTML("<=")
  23. stplkey := fmt.Sprintf("%s_%s_select.tpl", controllername, apiname)
  24. result, err := db.SqlTemplateClient(stplkey, &params).Query().List()
  25. if err != nil {
  26. fmt.Println(err)
  27. return nil, err
  28. }
  29. stplkey = fmt.Sprintf("%s_%s_count.tpl", controllername, apiname)
  30. cresult, err := db.SqlTemplateClient(stplkey, &params).Query().List()
  31. if err != nil {
  32. fmt.Println(err)
  33. return nil, err
  34. }
  35. if result == nil {
  36. presult := types.PageResult{}
  37. content := []map[string]interface{}{}
  38. presult.Page = (page)
  39. presult.Rows = (rows)
  40. presult.Content = content
  41. presult.TotalSize = 0
  42. presult.TotalPageSize = 0
  43. return &presult, nil
  44. }
  45. var records int64
  46. if len(cresult) > 0 {
  47. records = cresult[0]["records"].(int64)
  48. }
  49. var totalPageSize int64 = 0
  50. if records < int64(rows) {
  51. totalPageSize = 1
  52. } else if records%int64(rows) == 0 {
  53. totalPageSize = records / int64(rows)
  54. } else {
  55. totalPageSize = records/int64(rows) + 1
  56. }
  57. presult := types.PageResult{}
  58. presult.Page = (page)
  59. presult.Rows = (rows)
  60. presult.Content = result
  61. presult.TotalSize = records
  62. presult.TotalPageSize = totalPageSize
  63. return &presult, nil
  64. }