CartService.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace App\Modules\Mini\Services;
  3. use App\Base\BaseService;
  4. use App\Models\Cart;
  5. use App\Models\Goods\Goods;
  6. use App\Models\Order\Order;
  7. use App\Models\User\User;
  8. class CartService extends BaseService
  9. {
  10. public function paginate(User $user, $params)
  11. {
  12. $p = Cart::where("user_id", $user->id)->orderByDesc("id")->paginate($params['page_size']);
  13. return [
  14. "total" => $p->total(),
  15. "page_total" => $p->lastPage(),
  16. "list" => array_map(function (Cart $model) {
  17. return [
  18. "id" => $model->id,
  19. "sn" => $model->sn,
  20. "name" => $model->goods->name,
  21. "en_name" => $model->goods->en_name,
  22. "thumb" => $model->thumb,
  23. "count" => $model->count,
  24. "custom" => $model->custom,
  25. ];
  26. }, $p->items()),
  27. ];
  28. }
  29. public function add(User $user, $params): Cart
  30. {
  31. $gid = $params['id'];
  32. $goods = Goods::findOrFail($gid);
  33. $cart = new Cart();
  34. $cart->user_id = $user->id;
  35. $cart->goods_id = $goods->id;
  36. $cart->count = $params['count'];
  37. $cart->extra = [
  38. "goods_name" => $goods->name,
  39. "goods_en_name" => $goods->en_name,
  40. "thumb" => $goods->thumb,
  41. "sn" => $goods->sn,
  42. "custom" => $params['custom'],
  43. ];
  44. $cart->save();
  45. return $cart;
  46. }
  47. public function update(User $user, $params)
  48. {
  49. $cart = Cart::where("id", $params['id'])->where("user_id", $user->id)->firstOrFail();
  50. if ($params['count']) {
  51. $cart->count = $params['count'];
  52. $cart->save();
  53. } else {
  54. $cart->delete();
  55. }
  56. return $cart;
  57. }
  58. public function ask(User $user, $params)
  59. {
  60. $params['source'] = Order::SOURCE_CART;
  61. return app(OrderService::class)->askByCart($user, $params);
  62. }
  63. }