validate()) { return $this->getModelError(); } try { Cart::cacheStatusSet(true); $goods = Goods::findOne(['id' => $this->goods_id]); if (!$goods) { throw new \Exception('商品不存在'); } if ($goods->goodsHub->type == 1) { throw new \Exception('虚拟商品不允许加入购物车'); } $attr = GoodsAttr::find()->alias('g')->where([ 'g.id' => $this->attr, 'g.goods_id' => $this->goods_id, 'g.is_delete' => 0, ])->innerJoinwith(['goods o' => function ($query) { $query->where([ 'o.id' => $this->goods_id, 'o.cx_mch_id' => $this->cx_mch_id, 'o.is_delete' => 0, 'o.status' => 1, ]); }])->one(); if (!$attr) { throw new \Exception('商品异常'); } $this->num = $this->num > $attr->stock ? $attr->stock : $this->num; if ($this->num <= 0) { throw new \Exception('数量为空或库存为空'); } $cart = Cart::findOne([ 'user_id' => $this->user_id, 'goods_id' => $this->goods_id, 'attr_id' => $this->attr, 'cx_mch_id' => $this->cx_mch_id, 'plugin_sign' => $this->plugin_sign, 'is_delete' => 0, ]); if (!$cart) { $cart = new Cart(); $cart->user_id = $this->user_id; $cart->goods_id = $this->goods_id; $cart->attr_id = $this->attr; $cart->num = 0; $cart->cx_mch_id = $this->cx_mch_id; $cart->plugin_sign = $this->plugin_sign; $cart->attr_info = (new Serializer())->encode(ArrayHelper::toArray($attr)); }; $cart->num += $this->num; if ($cart->num > $attr->stock) { return $this->apiReturnError('商品加购件数超过库存'); } if ($cart->save()) { return $this->apiReturnSuccess('添加购物车成功'); } else { throw new \Exception($this->getModelError($cart)); } } catch (\Exception $e) { return $this->apiReturnError($e->getMessage()); } } public function __destruct() { Cart::cacheStatusSet(false); } }