BaseModel.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. <?php
  2. /**
  3. * Author: luzheng.liu
  4. * Time: 2020/10/19 22:42
  5. */
  6. namespace app\index\model;
  7. use app\common\until\Until;
  8. use think\Model;
  9. class BaseModel extends Model {
  10. private $where = [];
  11. private $page = 1;
  12. private $pageSize = 10;
  13. private $sort = false;
  14. private $sortWhere = '';
  15. /**
  16. * @param Model $objectModel
  17. * @return array
  18. * @throws \think\db\exception\DataNotFoundException
  19. * @throws \think\db\exception\DbException
  20. * @throws \think\db\exception\ModelNotFoundException
  21. */
  22. public function getPageList(BaseModel $objectModel) {
  23. $count = $objectModel::where($this->getWhere())->count();
  24. if ($count) {
  25. $order = [];
  26. if ($this->isSort()) {
  27. $order['sort'] = 'desc';
  28. }
  29. if (empty($this->sortWhere)){
  30. $order['id'] = 'desc';
  31. }else {
  32. $order[$this->getSortWhere()] = 'desc';
  33. }
  34. $list = $objectModel::where($this->getWhere())->order($order)->page($this->getPage(), $this->getPageSize())->select();
  35. $list = Until::modelToArray($list);
  36. }
  37. return [
  38. 'count' => $count,
  39. 'pageCount' => $count ? ceil($count / $this->getPageSize()) : 0,
  40. 'page' => $this->getPage(),
  41. 'pageSize' => $this->getPageSize(),
  42. 'list' => $count ? $list : []
  43. ];
  44. }
  45. /**
  46. * @return array
  47. */
  48. public function getWhere(): array {
  49. return $this->where;
  50. }
  51. /**
  52. * @param array $where
  53. */
  54. public function setWhere(array $where) {
  55. $this->where = $where;
  56. }
  57. /**
  58. * @return int
  59. */
  60. public function getPage(): int {
  61. return $this->page;
  62. }
  63. /**
  64. * @param int $page
  65. */
  66. public function setPage(int $page) {
  67. $this->page = $page;
  68. }
  69. /**
  70. * @return int
  71. */
  72. public function getPageSize(): int {
  73. return $this->pageSize;
  74. }
  75. /**
  76. * @param int $pageSize
  77. */
  78. public function setPageSize(int $pageSize) {
  79. $this->pageSize = $pageSize;
  80. }
  81. /**
  82. * @return bool
  83. */
  84. public function isSort(): bool {
  85. return $this->sort;
  86. }
  87. /**
  88. * @param bool $sort
  89. */
  90. public function setSort(bool $sort) {
  91. $this->sort = $sort;
  92. }
  93. /**
  94. * @return string
  95. */
  96. public function getSortWhere(): string {
  97. return $this->sortWhere;
  98. }
  99. /**
  100. * @param string $sortWhere
  101. */
  102. public function setSortWhere(string $sortWhere) {
  103. $this->sortWhere = $sortWhere;
  104. }
  105. }