StoreCart.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\model\api;
  4. use think\Model;
  5. /**
  6. * @mixin \think\Model
  7. */
  8. class StoreCart extends Model
  9. {
  10. protected $name = 'store_cart';
  11. /**
  12. * 获取购物车列表
  13. * @param int $uid
  14. * @return array
  15. */
  16. public function getCartList($uid)
  17. {
  18. $list = $this->alias('c')
  19. ->field('c.*,p.title,p.image,p.price as product_price')
  20. ->leftJoin('store_product p', 'p.id = c.product_id')
  21. ->where('c.uid', $uid)
  22. ->select()
  23. ->toArray();
  24. return $list;
  25. }
  26. /**
  27. * 添加购物车
  28. * @param array $data
  29. * @return int|false 成功返回购物车ID,失败返回false
  30. */
  31. public function addToCart($data)
  32. {
  33. // 检查是否已存在
  34. $exist = $this->where('uid', $data['uid'])
  35. ->where('product_id', $data['product_id'])
  36. ->where('product_attr_unique', $data['product_attr_unique'] ?? '')
  37. ->find();
  38. if ($exist) {
  39. // 更新数量
  40. $result = $this->where('id', $exist['id'])->inc('cart_num', $data['cart_num'])->update();
  41. return $result ? $exist['id'] : false;
  42. } else {
  43. // 新增
  44. $result = $this->insert($data);
  45. return $result ? $this->getLastInsID() : false;
  46. }
  47. }
  48. /**
  49. * 修改购物车数量
  50. * @param int $id
  51. * @param int $cartNum
  52. * @param int $uid
  53. * @return bool
  54. */
  55. public function updateCartNum($id, $cartNum, $uid)
  56. {
  57. return $this->where('id', $id)->where('uid', $uid)->update(['cart_num' => $cartNum]);
  58. }
  59. /**
  60. * 删除购物车
  61. * @param array $ids
  62. * @param int $uid
  63. * @return bool
  64. */
  65. public function deleteCart($ids, $uid)
  66. {
  67. return $this->where('uid', $uid)->whereIn('id', $ids)->delete();
  68. }
  69. }