where(['goods_id' => $goodsId]) ->andWhere(['user_id' => Yii::$app->user->getId()]) ->one(); if ($cart) { if (!$cart->updateCounters(['goods_count' => $count])) { throw new ServerErrorHttpException('服务器添加购物车商品失败'); } } else { $cart = $this->create($goodsId, $skuId, $count); } Helper::createdResponse($cart, $this->viewAction); return $cart; } /** * @param int $type * @return bool * @throws BadRequestHttpException * @throws NotFoundHttpException */ public function addOrSubGoods($type) { if (empty($type) || ($type != self::TYPE_SUB && $type != self::TYPE_ADD)) { throw new BadRequestHttpException('无效参数'); } $cart = $this->findCart(); if (!$cart) { throw new NotFoundHttpException('未找到该购物车'); } if ($cart->goods_count == 1 && $type == self::TYPE_SUB) { throw new BadRequestHttpException('购物商品需至少1件'); } return $cart->updateCounters(['goods_count' => $type]); } /** * @throws NotFoundHttpException * @throws ServerErrorHttpException * @throws \Throwable * @throws \yii\db\StaleObjectException * 删除购物车 */ public function delete() { $cart = $this->findCart(); if (!$cart) { throw new NotFoundHttpException('未找到该购物车'); } if ($cart->delete()) { Yii::$app->getResponse()->setStatusCode(204); } else { throw new ServerErrorHttpException('服务器无法删除购物车'); } } /** * @param $goodsId * @param $skuId * @param $count * @return Cart; * 创建新购物车 * @throws ServerErrorHttpException * @throws NotFoundHttpException */ private function create($goodsId, $skuId, $count) { $goods = Goods::findOne($goodsId); if (!$goods) { throw new NotFoundHttpException('商品未找到'); } $cart = new Cart(); $cart->goods_id = $goods->id; $cart->user_id = Yii::$app->user->getId(); $cart->goods_count = $count; $cart->sku_id = $skuId ?: 0; $cart->goods_img = $goods->image; $cart->goods_name = $goods->name; $cart->goods_price = Helper::countPrice($goodsId, $skuId); if (!$cart->save()) { throw new ServerErrorHttpException('服务器创建购物车失败'); } return $cart; } /** * @return ActiveRecord|null|Cart * 获取购物车实例 */ private function findCart() { $id = Yii::$app->request->getQueryParam('id'); return Cart::find() ->where(['id' => $id]) ->andWhere(['user_id' => Yii::$app->user->getId()]) ->one(); } }