page_util.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package utils
  2. import (
  3. "fmt"
  4. "git.qianqiusoft.com/qianqiusoft/light-apiengine/models"
  5. "github.com/xormplus/xorm"
  6. )
  7. // 分页查询
  8. func PageSearch(engine *xorm.Engine, controllername string, apiname string, tableName string, paramMap map[string]interface{}) (*models.PageResult, error) {
  9. page := paramMap["page"].(int)
  10. rows := paramMap["rows"].(int)
  11. offset := (page - 1) * rows
  12. paramMap["offset"] = offset
  13. stplkey := fmt.Sprintf("%s_%s_select.tpl", controllername, apiname)
  14. result, err := engine.SqlTemplateClient(stplkey, &paramMap).Query().List()
  15. if err != nil {
  16. fmt.Println(err)
  17. return nil, err
  18. }
  19. stplkey = fmt.Sprintf("%s_%s_count.tpl", controllername, apiname)
  20. cresult, err := engine.SqlTemplateClient(stplkey, &paramMap).Query().List()
  21. if err != nil {
  22. fmt.Println(err)
  23. return nil, err
  24. }
  25. // 无数据
  26. if result == nil {
  27. presult := models.PageResult{}
  28. content := []interface{}{}
  29. presult.Page = (page)
  30. presult.Rows = (rows)
  31. presult.Content = content
  32. presult.TotalSize = 0
  33. presult.TotalPageSize = 0
  34. return &presult, nil
  35. }
  36. records := cresult[0]["records"].(int64)
  37. var totalPageSize int64 = 0
  38. if totalPageSize < int64(rows) {
  39. totalPageSize = 1
  40. } else if records%int64(rows) == 0 {
  41. totalPageSize = records / int64(rows)
  42. } else {
  43. totalPageSize = records / int64(rows+1)
  44. }
  45. presult := models.PageResult{}
  46. presult.Page = (page)
  47. presult.Rows = (rows)
  48. presult.Content = result
  49. presult.TotalSize = records
  50. presult.TotalPageSize = totalPageSize
  51. return &presult, nil
  52. }