Cart.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. namespace app\common\Service;
  3. use app\common\model\Carts;
  4. use think\Exception;
  5. class Cart
  6. {
  7. /**
  8. * 将购物车数据转换为标准的商品列表格式
  9. * @param array $cart_ids 购物车ID列表
  10. * @param int $user_id 用户ID
  11. * @return array
  12. * @throws Exception
  13. */
  14. public static function convertCartToGoodsList($cart_ids, $user_id)
  15. {
  16. // 查询购物车数据
  17. $cartItems = Carts::where('id', 'in', $cart_ids)
  18. ->where('user_id', $user_id)
  19. ->select();
  20. if (empty($cartItems)) {
  21. throw new Exception("购物车数据不存在");
  22. }
  23. $goods_list = [];
  24. foreach ($cartItems as $cart) {
  25. $goods_list[] = [
  26. 'goods_id' => $cart->goods_id,
  27. 'goods_sku_id' => $cart->goods_sku_id,
  28. 'nums' => $cart->nums
  29. ];
  30. }
  31. return $goods_list;
  32. }
  33. /**
  34. * @ DateTime 2021-05-31
  35. * @ 获取购物车商品列表
  36. * @param string $ids
  37. * @param integer $user_id
  38. * @param integer $sceneval
  39. * @return array
  40. */
  41. public static function getGoodsList($ids, $user_id)
  42. {
  43. return Carts::field("c.*,GROUP_CONCAT(sp.name,':',sv.value order by sp.id asc) sku_attr")
  44. ->with([
  45. 'Goods' => function ($query) {
  46. $query->where('status', 'normal');
  47. },
  48. 'Sku'
  49. ])
  50. ->alias('c')
  51. ->join('shop_goods_sku sku', 'c.goods_sku_id=sku.id', 'LEFT')
  52. ->join('shop_goods_sku_spec p', "FIND_IN_SET(p.id,sku.sku_id)", 'LEFT')
  53. ->join('shop_spec sp', 'sp.id=p.spec_id', 'LEFT')
  54. ->join('shop_spec_value sv', 'sv.id=p.spec_value_id', 'LEFT')
  55. ->where(function ($query) use ($ids) {
  56. if ($ids) {
  57. $query->where('c.id', 'in', $ids);
  58. }
  59. })
  60. ->where('c.user_id', $user_id)
  61. ->order('c.createtime desc')
  62. ->group('c.id')
  63. ->select();
  64. }
  65. /**
  66. * 添加商品到购物车
  67. *
  68. * @param string $goods_id 商品ID
  69. * @param string $goods_sku_id 商品SKUID
  70. * @param int $nums 数量
  71. * @param int $user_id 会员ID
  72. * @return mixed
  73. */
  74. public static function push($goods_id, $goods_sku_id, $nums = 1, $user_id = 0)
  75. {
  76. $row = Carts::where('goods_id', $goods_id)
  77. ->where('goods_sku_id', $goods_sku_id)
  78. ->where('user_id', $user_id)
  79. ->find();
  80. //已存在,数量加
  81. if ($row) {
  82. $row->setInc('nums', $nums);
  83. } else {
  84. $row = new Carts();
  85. $row->save([
  86. 'goods_id' => $goods_id,
  87. 'goods_sku_id' => $goods_sku_id,
  88. 'user_id' => $user_id,
  89. 'nums' => $nums
  90. ]);
  91. }
  92. return $row->id;
  93. }
  94. /**
  95. * 清空购物车
  96. */
  97. public static function clear($cart_ids)
  98. {
  99. Carts::where('id', 'IN', $cart_ids)->delete();
  100. }
  101. }