BaseActiveRecord.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace addons\OperationCenter\common\models;
  3. use yii\helpers\Json;
  4. use yii\data\Pagination;
  5. use addons\OperationCenter\common\models\traits\SoftDeleteTrait;
  6. use common\models\base\BaseActiveRecord as BaseBaseActiveRecord;
  7. /**
  8. * BaseActiveRecord class
  9. * @package addons\OperationCenter\common\models
  10. */
  11. class BaseActiveRecord extends BaseBaseActiveRecord
  12. {
  13. use SoftDeleteTrait;
  14. /**
  15. * 获取分页数据
  16. *
  17. * @param integer $page
  18. * @param integer $limit
  19. * @param callable $callback
  20. * @param string $order_by
  21. * @return array
  22. */
  23. public static function getPageList(
  24. int $page, int $limit, callable $callback, string $order_by = 'id desc'
  25. ) :array
  26. {
  27. $model = static::find();
  28. if (!empty($callback)) call_user_func($callback, $model);
  29. $pagination = new Pagination(['totalCount' => $model->count(), 'pageSize' => $limit]);
  30. $model->limit($pagination->limit)->offset($pagination->offset);
  31. $list = $model->asArray()->orderBy($order_by)->all();
  32. $data['list'] = $list;
  33. $data['page_count'] = $pagination->pageCount;
  34. $data['current_page'] = $page + 1;
  35. return $data;
  36. }
  37. /**
  38. * @param array $data
  39. * @return array
  40. */
  41. public function jsonEncode(array $data)
  42. {
  43. $json_keys = $this->json_keys ?? [];
  44. foreach ($json_keys as $key) {
  45. // !empty($data[$key]) && ($data[$key] = Json::encode($data[$key]));
  46. // 默认
  47. $data[$key] = !empty($data[$key]) ? $data[$key] : [];
  48. $data[$key] = Json::encode($data[$key]);
  49. }
  50. return $data;
  51. }
  52. /**
  53. * @return static
  54. */
  55. public function jsonDecode()
  56. {
  57. $json_keys = $this->json_keys ?? [];
  58. foreach ($json_keys as $key) {
  59. !empty($this->$key) && ($this->$key = Json::decode($this->$key));
  60. }
  61. return $this;
  62. }
  63. /**
  64. * @param boolean $runValidation
  65. * @param array $attributeNames
  66. * @return true|static
  67. */
  68. public function save($runValidation = true, $attributeNames = null)
  69. {
  70. $res = parent::save($runValidation = true, $attributeNames = null);
  71. return $res === true
  72. ? true
  73. : $this;
  74. }
  75. }