ServiceTrait.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace app\common\traits;
  3. use app\common\service\CommonService;
  4. trait ServiceTrait
  5. {
  6. public static $instance;
  7. /** @var CommonService */
  8. public static $Common = CommonService::class;
  9. /**
  10. * 单例获取当前服务
  11. * @return static
  12. */
  13. public static function instance()
  14. {
  15. if (is_null(static::$instance)) {
  16. static::$instance = new static();
  17. }
  18. return static::$instance;
  19. }
  20. /**
  21. * 获取单条数据
  22. * @param $where
  23. * @param string|array $with
  24. * @param string|array $order
  25. * @return mixed
  26. */
  27. public static function getOne($where, $with = [], $order = [], $params = [])
  28. {
  29. $model = self::$Model::with($with)->where($where);
  30. if ($order) {
  31. $model->order($order[0] ?? 'id', $order[1] ?? 'asc');
  32. }
  33. if (!empty($params['withCount'])) {
  34. $model->withCount($params['withCount']);
  35. }
  36. return $model->find();
  37. }
  38. /**
  39. * 获取列表数据
  40. * @param $where
  41. * @param int $page_size
  42. * @param string|array $order --'id desc,status'|['order','id'=>'desc']
  43. * @param string $group
  44. * @param string|array $with
  45. * @param array $params
  46. * @return mixed
  47. */
  48. public static function getList($where, $page_size = 0, $order = [], $group = '', $with = [], $params = [])
  49. {
  50. $model = self::$Model::where($where);
  51. if ($order) {
  52. $model->order($order);
  53. }
  54. if ($group) {
  55. $model->group($group);
  56. }
  57. if ($with) {
  58. $model->with($with);
  59. }
  60. if (!empty($params['withCount'])) {
  61. $model->withCount($params['withCount']);
  62. }
  63. $res = $page_size ? $model->paginate($page_size, false, $params['config'] ?? []) : $model->select();
  64. return $res;
  65. }
  66. /**
  67. * 调用模型静态方法
  68. * @param $funName
  69. * @param $args
  70. * @return mixed
  71. */
  72. public static function __callStatic($funName, $args)
  73. {
  74. $res = self::$Model::$funName(...$args);
  75. return $res;
  76. }
  77. }