Example #1
0
 public function actionOrder()
 {
     $session = Yii::$app->getSession();
     $cart = $session->has('cart') ? $session->get('cart') : [];
     if (!$cart) {
         return $this->redirect(['index']);
     }
     $model = new Order();
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         if (is_array($cart)) {
             foreach ($cart as $one_goods) {
                 $order_goods = new OrderGoods();
                 $order_goods->goods_id = $one_goods['id'];
                 $order_goods->count = $one_goods['count'];
                 $order_goods->order_id = $model->id;
                 $order_goods->save();
             }
         }
         Yii::$app->session->remove('cart');
         return $this->redirect(['index']);
     } else {
         $goods_id = ArrayHelper::getColumn($cart, 'id');
         $goods = Goods::find()->where(['id' => $goods_id])->asArray()->indexBy('id')->all();
         $amount = 0;
         foreach ($cart as $one_goods) {
             $amount += $one_goods['count'] * $goods[$one_goods['id']]['price'];
         }
         $model->price = $amount;
         return $this->render('order', ['cart' => $cart, 'model' => $model, 'amount' => $amount]);
     }
 }