海南旅游SAAS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.2 KiB

  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\AgentProduct;
  5. use App\Models\UserFav;
  6. class UserFavController extends Controller
  7. {
  8. public function index()
  9. {
  10. $page = request()->input('page');
  11. if ($page && !ctype_digit($page)) {
  12. return $this->error('页码错误');
  13. }
  14. $list = UserFav::query()->with([
  15. 'agentProduct' => fn($query) => $query->select('id', 'price', 'original_price'),
  16. 'product' => fn($query) => $query->select('id', 'title', 'pictures'),
  17. ])
  18. ->where('user_id', $this->user_id)
  19. ->select('id', 'agent_product_id', 'product_id', 'created_at')
  20. ->orderBy('id', 'DESC')
  21. ->simplePaginate(15);
  22. return $this->success($list);
  23. }
  24. public function create()
  25. {
  26. $id = request()->input('id');
  27. if (!$id || !ctype_digit($id)) {
  28. return $this->error('无效的ID');
  29. }
  30. $agent_product = AgentProduct::find($id);
  31. if (!$agent_product) {
  32. return $this->error('产品不存在或已被删除');
  33. }
  34. //如果不存在则创建
  35. UserFav::query()->firstOrCreate([
  36. 'user_id' => $this->user_id,
  37. 'agent_product_id' => $agent_product->id,
  38. 'product_id' => $agent_product->product_id,
  39. ]);
  40. return $this->success();
  41. }
  42. }