海南旅游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.

80 lines
1.9 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. use Illuminate\Support\Facades\Storage;
  7. /**
  8. * 用户收藏
  9. * Class UserFavController
  10. * @package App\Http\Controllers\Api
  11. */
  12. class UserFavController extends Controller
  13. {
  14. public function index()
  15. {
  16. $list = UserFav::query()
  17. ->with([
  18. 'agentProduct:id,price,original_price,title,pictures',
  19. ])
  20. ->where('user_id', $this->user_id)
  21. ->select('id', 'agent_product_id', 'product_id', 'created_at')
  22. ->orderBy('id', 'DESC')
  23. ->simplePaginate(15);
  24. if (!$list->isEmpty()) {
  25. $list = $list->toArray();
  26. $prefix = Storage::disk('public')->url('');
  27. if ($list['data']) {
  28. foreach ($list['data'] as &$v) {
  29. if (!empty($v['agent_product']['pictures'])) {
  30. //多图
  31. $v['agent_product']['pictures'] = array_map(function ($v) use ($prefix) {
  32. return strpos($v, $prefix) === false ? $prefix . $v : $v;
  33. }, $v['agent_product']['pictures']);
  34. //单图
  35. $v['agent_product']['picture'] = $prefix . $v['agent_product']['picture'];
  36. }
  37. }
  38. }
  39. }
  40. return $this->success($list);
  41. }
  42. public function create()
  43. {
  44. $id = (int)request()->input('agent_product_id');
  45. $agent_product = AgentProduct::find($id);
  46. if (!$agent_product) {
  47. return $this->error('产品不存在或已被删除');
  48. }
  49. //如果不存在则创建
  50. UserFav::query()->firstOrCreate([
  51. 'user_id' => $this->user_id,
  52. 'agent_product_id' => $agent_product->id,
  53. 'product_id' => $agent_product->product_id,
  54. ]);
  55. return $this->success();
  56. }
  57. public function delete()
  58. {
  59. $id = (int)request()->input('agent_product_id');
  60. $fav = UserFav::query()->where([
  61. 'user_id' => $this->user_id,
  62. 'agent_product_id' => $id,
  63. ])->first();
  64. if (!$fav) {
  65. return $this->error('收藏不存在');
  66. }
  67. $fav->delete();
  68. return $this->success();
  69. }
  70. }