page_utils.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. }
  18. offset := (page - 1) * rows
  19. params["offset"] = offset
  20. params["ge"] = template.HTML(">=")
  21. params["le"] = template.HTML("<=")
  22. stplkey := fmt.Sprintf("%s_%s_select.tpl", controllername, apiname)
  23. result, err := db.SqlTemplateClient(stplkey, &params).Query().List()
  24. if err != nil {
  25. fmt.Println(err)
  26. return nil, err
  27. }
  28. stplkey = fmt.Sprintf("%s_%s_count.tpl", controllername, apiname)
  29. cresult, err := db.SqlTemplateClient(stplkey, &params).Query().List()
  30. if err != nil {
  31. fmt.Println(err)
  32. return nil, err
  33. }
  34. if result == nil {
  35. presult := types.PageResult{}
  36. content := []interface{}{}
  37. presult.Page = (page)
  38. presult.Rows = (rows)
  39. presult.Content = content
  40. presult.TotalSize = 0
  41. presult.TotalPageSize = 0
  42. return &presult, nil
  43. }
  44. var records int64
  45. if len(cresult) > 0 {
  46. records = cresult[0]["records"].(int64)
  47. }
  48. var totalPageSize int64 = 0
  49. if records < int64(rows) {
  50. totalPageSize = 1
  51. } else if records%int64(rows) == 0 {
  52. totalPageSize = records / int64(rows)
  53. } else {
  54. totalPageSize = records/int64(rows) + 1
  55. }
  56. presult := types.PageResult{}
  57. presult.Page = (page)
  58. presult.Rows = (rows)
  59. presult.Content = result
  60. presult.TotalSize = records
  61. presult.TotalPageSize = totalPageSize
  62. return &presult, nil
  63. }