ProductController.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /**
  3. * Created by PhpStorm
  4. * DateTime: 2022/10/2 13:32
  5. *
  6. * @description
  7. */
  8. namespace App\Http\Controllers\V1;
  9. use App\Models\Product;
  10. use App\Models\ProductCategory;
  11. use App\Models\StatProduct;
  12. use App\Models\StatProductDownload;
  13. use Dingo\Api\Http\Request;
  14. use Illuminate\Database\Eloquent\Builder;
  15. use Illuminate\Http\JsonResponse;
  16. class ProductController extends Controller
  17. {
  18. public function cate(Request $request): JsonResponse
  19. {
  20. $limit = $request->input('limit', 3);
  21. $keywords = $request->input('keywords', '');
  22. $page = request()->input('page',1);
  23. $offset = ($page - 1) * $limit;
  24. $lists = ProductCategory::where('is_opened', 1)
  25. ->when($keywords, function ($query, $keywords) {
  26. /* @var Builder $query*/
  27. return $query->where('name','like', "%$keywords%");
  28. })
  29. ->orderByDesc('sort')
  30. ->limit($limit)
  31. ->offset($offset)
  32. ->get();
  33. return $this->success($lists);
  34. }
  35. public function search(Request $request): JsonResponse
  36. {
  37. $limit = $request->input('limit');
  38. $keywords = $request->input('keywords', '');
  39. $page = request()->input('page',1);
  40. $cateId = request()->input('cate_id',0);
  41. $offset = ($page - 1) * $limit;
  42. $lists = Product::withCount(['viewer'])->where('is_opened', 1)
  43. ->when($keywords, function ($query, $keywords) {
  44. /* @var Builder $query*/
  45. return $query->where('name','like', "%$keywords%");
  46. })
  47. ->when($cateId, function ($query, $cateId) {
  48. /* @var Builder $query*/
  49. return $query->where('cate_id', $cateId);
  50. })
  51. ->orderByDesc('viewer_count')
  52. ->orderByDesc('sort')
  53. ->limit($limit)
  54. ->offset($offset)
  55. ->get();
  56. return $this->success($lists);
  57. }
  58. public function detail($id): JsonResponse
  59. {
  60. $info = Product::with(['specs' => function($query) {
  61. $query->select(['id','product_id','name','specs'])
  62. ->where('is_opened', 1)
  63. ->orderByDesc('sort');
  64. }])
  65. ->where('id',$id)
  66. ->first();
  67. $info->files = $info;
  68. return $this->success($info);
  69. }
  70. public function viewer($id): JsonResponse
  71. {
  72. $stat = new StatProduct();
  73. $stat->product_id = $id;
  74. $stat->user_id = \user()->id;
  75. $stat->save();
  76. return $this->success();
  77. }
  78. public function download($id): JsonResponse
  79. {
  80. $stat = new StatProductDownload();
  81. $stat->product_id = $id;
  82. $stat->user_id = \user()->id;
  83. $stat->save();
  84. return $this->success();
  85. }
  86. }