public function actionIndex() { Yii::$app->session['step'] = 1; if (Yii::$app->request->get('type') && Yii::$app->request->get('product_id')) { $type = Yii::$app->request->get('type'); $productId = Yii::$app->request->get('product_id'); $product = Product::findOne($productId); $cartProduct = Cart::find()->where(['session_id' => Yii::$app->session->id, 'product_id' => $productId])->one(); if ($type == 'minus' && $cartProduct->number > 1) { //减少一个 Cart::updateAllCounters(['number' => -1], ['session_id' => Yii::$app->session->id, 'product_id' => $productId]); } elseif ($type == 'add' && $cartProduct->number < $product->stock) { //增加一个 Cart::updateAllCounters(['number' => 1], ['session_id' => Yii::$app->session->id, 'product_id' => $productId]); } elseif ($type == 'change' && Yii::$app->request->get('value')) { //修改为指定的数量 $productId = Yii::$app->request->get('change'); $value = Yii::$app->request->get('value'); Cart::updateAll(['number' => $value], ['session_id' => Yii::$app->session->id, 'product_id' => $productId]); } Cart::deleteAll('number <= 0'); return; } $products = Cart::find()->where(['or', 'session_id = "' . Yii::$app->session->id . '"', 'user_id = ' . (Yii::$app->user->id ? Yii::$app->user->id : -1)])->all(); if (count($products)) { // 如果购物车的数量大于商品的库存,则设置为最大的库存 return $this->render('index', ['products' => $products]); } else { return $this->render('cart-no-product', ['products' => $products]); } }
/** * This method is called after the user is successfully logged in. * The default implementation will trigger the [[EVENT_AFTER_LOGIN]] event. * If you override this method, make sure you call the parent implementation * so that the event is triggered. * @param IdentityInterface $identity the user identity information * @param boolean $cookieBased whether the login is cookie-based * @param integer $duration number of seconds that the user can remain in logged-in status. * If 0, it means login till the user closes the browser or the session is manually destroyed. */ protected function afterLogin($identity, $cookieBased, $duration) { $carts = Cart::find()->where(['session_id' => $this->oldSessionId])->all(); foreach ($carts as $cart) { $exist = Cart::find()->where(['user_id' => $identity->id, 'product_id' => $cart->product_id])->one(); if ($exist) { Cart::updateAllCounters(['number' => $cart->number], ['user_id' => $identity->id]); Cart::deleteAll(['session_id' => $this->oldSessionId, 'product_id' => $cart->product_id]); } else { Cart::updateAll(['session_id' => Yii::$app->session->id, 'user_id' => $identity->id], ['session_id' => $this->oldSessionId, 'product_id' => $cart->product_id]); } } Cart::updateAll(['session_id' => Yii::$app->session->id], ['user_id' => $identity->id]); //Cart::updateAll(['session_id' => Yii::$app->session->id, 'user_id' => $identity->id], ['session_id' => $this->oldSessionId]); return parent::afterLogin($identity, $cookieBased, $duration); }