Carts.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace app\common\model;
  3. use think\Cookie;
  4. use think\Model;
  5. /**
  6. * 模型
  7. */
  8. class Carts extends Model
  9. {
  10. // 表名
  11. protected $name = 'shop_carts';
  12. // 开启自动写入时间戳字段
  13. protected $autoWriteTimestamp = 'int';
  14. // 定义时间戳字段名
  15. protected $createTime = 'createtime';
  16. protected $updateTime = '';
  17. // 追加属性
  18. protected $append = [];
  19. /**
  20. * @ DateTime 2021-05-31
  21. * @ 获取购物车商品列表
  22. * @param string $ids
  23. * @param integer $user_id
  24. * @param integer $sceneval
  25. * @return array
  26. */
  27. public static function getGoodsList($ids, $user_id)
  28. {
  29. return (new self())->field("c.*,GROUP_CONCAT(sp.name,':',sv.value order by sp.id asc) sku_attr")
  30. ->with([
  31. 'Goods' => function ($query) {
  32. $query->where('status', 'normal');
  33. },
  34. 'Sku'
  35. ])
  36. ->alias('c')
  37. ->join('shop_goods_sku sku', 'c.goods_sku_id=sku.id', 'LEFT')
  38. ->join('shop_goods_sku_spec p', "FIND_IN_SET(p.id,sku.sku_id)", 'LEFT')
  39. ->join('shop_spec sp', 'sp.id=p.spec_id', 'LEFT')
  40. ->join('shop_spec_value sv', 'sv.id=p.spec_value_id', 'LEFT')
  41. ->where(function ($query) use ($ids) {
  42. if ($ids) {
  43. $query->where('c.id', 'in', $ids);
  44. }
  45. })
  46. ->where('c.user_id', $user_id)
  47. ->order('c.createtime desc')
  48. ->group('c.id')
  49. ->select();
  50. }
  51. /**
  52. * 添加商品到购物车
  53. *
  54. * @param string $goods_id 商品ID
  55. * @param string $goods_sku_id 商品SKUID
  56. * @param int $nums 数量
  57. * @param int $user_id 会员ID
  58. * @return mixed
  59. */
  60. public static function push($goods_id, $goods_sku_id, $nums = 1, $user_id = 0)
  61. {
  62. $row = (new self)->where('goods_id', $goods_id)
  63. ->where('goods_sku_id', $goods_sku_id)
  64. ->where('user_id', $user_id)
  65. ->find();
  66. //已存在,数量加
  67. if ($row) {
  68. $row->setInc('nums', $nums);
  69. } else {
  70. $row = (new self);
  71. $row->save([
  72. 'goods_id' => $goods_id,
  73. 'goods_sku_id' => $goods_sku_id,
  74. 'user_id' => $user_id,
  75. 'nums' => $nums
  76. ]);
  77. }
  78. return $row->id;
  79. }
  80. /**
  81. * 清空购物车
  82. */
  83. public static function clear($cart_ids)
  84. {
  85. self::where('id', 'IN', $cart_ids)->delete();
  86. }
  87. public function Goods()
  88. {
  89. return $this->belongsTo('Goods', 'goods_id', 'id', [], 'LEFT');
  90. }
  91. public function Sku()
  92. {
  93. return $this->belongsTo('Sku', 'goods_sku_id', 'id', [], 'LEFT');
  94. }
  95. }