ViewService.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\DB;
  4. use Illuminate\Support\Facades\Log;
  5. /**
  6. * 视图管理
  7. */
  8. class ViewService
  9. {
  10. /**
  11. * 获取视图列表
  12. *
  13. * @param string $viewName 视图名称
  14. * @param array $whereParams 查询参数
  15. * @param array $pageParams 分页参数
  16. * @param array $sortParams 排序参数
  17. */
  18. public function viewList($viewName, array $whereParams, array $pageParams, array $sortParams = []): array
  19. {
  20. try {
  21. // 尝试获取对应的模型类名
  22. $modelClass = 'App\\Models\\' . str_replace(' ', '', ucwords(str_replace('_', ' ', $viewName)));
  23. // 检查模型是否存在
  24. if (class_exists($modelClass)) {
  25. $query = app($modelClass)->query();
  26. } else {
  27. $query = DB::table($viewName);
  28. }
  29. // 条件筛选
  30. foreach ($whereParams as $key => $value) {
  31. if (is_string($value)) {
  32. $query->where($key, 'like', "%{$value}%");
  33. } else {
  34. $query->where($key, $value);
  35. }
  36. }
  37. // 排序
  38. if (! empty($sortParams)) {
  39. $query->orderBy($sortParams['orderBy'], $sortParams['orderDir']);
  40. }
  41. $result = $query->paginate($pageParams['perPage'], ['*'], 'page', $pageParams['page']);
  42. return [
  43. 'data' => [
  44. 'items' => $result->items(),
  45. 'total' => $result->total(),
  46. ],
  47. 'msg' => 'success',
  48. 'status' => 0,
  49. ];
  50. } catch (\Exception $e) {
  51. Log::error('获取视图数据失败', [
  52. 'view_name' => $viewName,
  53. 'error' => $e->getMessage(),
  54. 'trace' => $e->getTraceAsString(),
  55. ]);
  56. return [
  57. 'data' => [
  58. 'items' => [],
  59. ],
  60. 'msg' => '获取数据失败',
  61. 'status' => 1,
  62. ];
  63. }
  64. }
  65. }