page_util.go 1.3 KB

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