Base.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace app\common\model;
  3. use think\Config as ThinkConfig;
  4. use think\Model;
  5. use think\Db;
  6. use think\Cache;
  7. class Base extends Model
  8. {
  9. protected $tablePrefix;
  10. protected $primaryId;
  11. protected $readFromMaster;
  12. //自定义初始化
  13. protected function initialize()
  14. {
  15. //需要调用`Model`的`initialize`方法
  16. parent::initialize();
  17. // 自定义的初始化
  18. $this->tablePrefix = isset($this->tablePrefix) ? $this->tablePrefix : ThinkConfig::get('database.prefix');
  19. $this->primaryId = isset($this->primaryId) ? $this->primaryId : $this->name . '_id';
  20. $this->readFromMaster = isset($this->readFromMaster) ? $this->readFromMaster : false;
  21. // 表创建或修改
  22. if (method_exists($this, 'createTableIfNotExists')) {
  23. $this->createTableIfNotExists();
  24. }
  25. }
  26. public function getCountByCond($cond)
  27. {
  28. $query_object = $this;
  29. if ($this->readFromMaster === true) {
  30. $query_object = $query_object->master();
  31. }
  32. return (int)$query_object->where($cond)->count();
  33. }
  34. public function getListByCond($offset, $limit, $cond, $orderby = '', $fields = "*", $transform = false)
  35. {
  36. $offset = max(0, (int)$offset);
  37. $limit = max(1, (int)$limit);
  38. if (empty($orderby)) {
  39. $orderby = $this->primaryId . " DESC";
  40. } else {
  41. if (strpos($orderby, $this->primaryId) === false) {
  42. $orderby .= ", " . $this->primaryId . " DESC";
  43. }
  44. }
  45. $query_object = $this;
  46. if ($this->readFromMaster === true) {
  47. $query_object = $query_object->master();
  48. }
  49. $list = $query_object->where($cond)->field($fields)->order($orderby)->limit($offset, $limit)->select();
  50. if (!$list) {
  51. return [];
  52. }
  53. $final = [];
  54. foreach ($list as $row) {
  55. $row_array = $row->getData();
  56. if ($transform !== false) {
  57. $row_array = $this->transformRow($row_array, $transform);
  58. }
  59. $final[] = $row_array;
  60. }
  61. return $final;
  62. }
  63. public function transformRow($row, $extends = []) {
  64. return $row;
  65. }
  66. }