where('user_id', $user_id) ->select(); if (empty($cartItems)) { throw new BusinessException("购物车数据不存在"); } $goods_list = []; foreach ($cartItems as $cart) { $goods_list[] = [ 'goods_id' => $cart->goods_id, 'goods_sku_id' => $cart->goods_sku_id, 'nums' => $cart->nums ]; } return $goods_list; } /** * @ DateTime 2021-05-31 * @ 获取购物车商品列表 * @param string $ids * @param integer $user_id * @param integer $sceneval * @return array */ public static function getGoodsList($ids, $user_id) { return Carts::field("c.*,GROUP_CONCAT(sp.name,':',sv.value order by sp.id asc) sku_attr") ->with([ 'Goods' => function ($query) { $query->where('status', GoodsEnum::STATUS_ON_SALE); }, 'Sku' ]) ->alias('c') ->join('shop_goods_sku sku', 'c.goods_sku_id=sku.id', 'LEFT') ->join('shop_goods_sku_spec p', "FIND_IN_SET(p.id,sku.spec_value_ids)", 'LEFT') ->join('shop_spec sp', 'sp.id=p.spec_id', 'LEFT') ->join('shop_spec_value sv', 'sv.id=p.spec_value_id', 'LEFT') ->where(function ($query) use ($ids) { if ($ids) { $query->where('c.id', 'in', $ids); } }) ->where('c.user_id', $user_id) ->order('c.createtime desc') ->group('c.id') ->select(); } /** * 添加商品到购物车 * * @param string $goods_id 商品ID * @param string $goods_sku_id 商品SKUID * @param int $nums 数量 * @param int $user_id 会员ID * @return mixed */ public static function push($goods_id, $goods_sku_id, $nums = 1, $user_id = 0) { $row = Carts::where('goods_id', $goods_id) ->where('goods_sku_id', $goods_sku_id) ->where('user_id', $user_id) ->find(); //已存在,数量加 if ($row) { $row->setInc('nums', $nums); } else { $row = new Carts(); $row->save([ 'goods_id' => $goods_id, 'goods_sku_id' => $goods_sku_id, 'user_id' => $user_id, 'nums' => $nums ]); } return $row->id; } /** * 清空购物车 */ public static function clear($cartIds,$userId) { Carts::where('id', 'IN', $cartIds)->where('user_id', $userId)->delete(); } // 删除购物车 public static function deleteCart($cartIds =[], $userId = 0) { return Carts::where('id', 'IN', $cartIds) ->where('user_id', $userId)->delete(); } /** * 批量更新购物车商品数量 * @param array $cart_ids 购物车ID数组 * @param array $goods_list 商品列表(包含goods_id, goods_sku_id, nums) * @param int $user_id 用户ID * @return void */ public static function updateCartByGoodsList($cartIds =[], $goodsList=[], $userId = 0) { if (empty($cartIds) || empty($goodsList)) return; // 以goods_id+goods_sku_id为key,nums为值 $goodsMap = []; foreach ($goodsList as $item) { $key = $item['goods_id'] . '_' . $item['goods_sku_id']; $goodsMap[$key] = $item['nums']; } // 查询购物车 $carts = Carts::where('id', 'in', $cartIds)->where('user_id', $userId)->select(); foreach ($carts as $cart) { $key = $cart->goods_id . '_' . $cart->goods_sku_id; if (isset($goodsMap[$key])) { // 只更新数量 $cart->nums = $goodsMap[$key]; $cart->save(); } } } public static function updateChecked($userId, $cartIds=[], $isChecked=0) { return Carts::where('user_id', $userId) ->whereIn('id', $cartIds) ->update(['checked' => $isChecked]); } }