Идентификатор продукта магазина Yii2, разделенный запятой - PullRequest
0 голосов
/ 31 октября 2018

Я хочу добавить proid в $ model-> product, который находится в другой таблице. Я хочу получить идентификатор продукта, который добавлен в корзину, и сохранить его в БД (phpmyadmin), разделенных запятой

controller.php (откуда я получаю сессию)

class CartController extends \yii\web\Controller
{
    public $totalItems=0;
    public $totalPrice=0.00;
    //public $netPrice = 0;

    public function actionAdd($id = null)
    {
        if(!intval($id) || empty($id)){
           Yii::$app->session->setFlash('error','cannot find this product');
            return $this->redirect('/front');

        }

        if(!isset(Yii::$app->session['cart'])){
            Yii::$app->session['cart'] = [];
            Yii::$app->session['total_items'] = 0;
            Yii::$app->session['total_price'] = 0.00;

        }
           $this->addtocart($id);

           $this->setTotal();
           //$model = new Orders();
           //$model->ordername = ;
              // $model->ordertotal = $netPrice ;
            return $this->redirect('index');


    }
    public function addtocart($id){
        if(isset(Yii::$app->session['cart'][$id])){
            $session = Yii::$app->session['cart'];
            $session[$id]= $session[$id] +=1;
            Yii::$app->session['cart']= $session;
        }
        else{
            $session = Yii::$app->session['cart'];
            $session[$id] = 1;
            Yii::$app->session['cart'] = $session;
        }
    }
    public function setTotal(){
        Yii::$app->session['total_items']=$this->totalItems(Yii::$app->session['cart']);
        Yii::$app->session['total_price']=$this->totalPrice(Yii::$app->session['cart']);

        $this->totalItems = Yii::$app->session['total_items'];
        $this->totalPrice = Yii::$app->session['total_price'];





    }
    public function totalItems($cart){
        $totalItems = 0;
        if(is_array($cart)){
            foreach ($cart as $id=>$qty){
                $totalItems += $qty;
            }

            return $totalItems;
        }
        //return $totalItems;
    }
    public function totalPrice($cart){
        $netPrice = 0.00;
        if(is_array($cart)){
            foreach ($cart as $id=>$qty){
                $item = $this->findProduct($id);
                $netPrice += $item->price * $qty;
            }
            //return $netPrice;
        }
        return $netPrice;
    }


    public function findProduct($id){
        return Products::findOne($id);
    }
    public function updateCart(){
        foreach(Yii::$app->session['cart'] as $id=>$qty){
            if(isset($_POST[$id])){
                if($_POST == 0){
                    $session = Yii::$app->session['cart'];
                    unset($session[$id]);
                    Yii::$app->session['cart'] = $session;
                }
                else{
                    $cart = Yii::$app->session['cart'];
                    $cart[$id] = $_POST[$id];
                    Yii::$app->session['cart'] = $cart;
                }
            }
        }
    }


    public function actionIndex()
    {
        if(!isset(Yii::$app->session['cart']) || empty(Yii::$app->session['cart'])){
            Yii::$app->session->setFlash('error','cart is empty');

        }
// i made a table named order with colums ordertotal and products where ordertotal should store the total value and products should store the product id which are added to cart got the order total but didn't get products
            $model = new Orders();
            $model->ordertotal = $this->totalPrice(Yii::$app->session['cart']); //got the order total from this 
           //$model->product=add the product id( <?= Html::a('AddToCart',['/cart/add','id'=> $p->proid], ['class' => 'btn btn-success']) ?> //this is my product page where i 'add to cart' from) seperated by comma

        if($model->save()){
            print_r('ok');

        }
        else{
           echo $model->getErrors();

        }



        return $this->render('index',[
            'totalItems' => $this->totalItems(Yii::$app->session['cart']),
            'totalPrice' => $this->totalPrice(Yii::$app->session['cart']),
        ]);
    }

}

я получил вышеуказанный код от t = PLX5MZfWdby5QFDLU-Ov7Ixv6AilU-mgcQ "

реализация новой модели и добавление ее в базу данных - моя реализация

product.php

<?php foreach ($product as $p) { ?>
                <div class="col-md-4">

                    <h2><?php echo $p->name?></h2>
                    <?php echo "<br/>"?>
                    <?php echo "Name: ".$p->name?>
                    <?php echo "<br/>"?>


                     <?php echo "price: ".$p->price?>
                    <?php echo "<br/>"?>
                    <?= Html::a('AddToCart',['/cart/add','id'=> $p->proid], ['class' => 'btn btn-success']) ?>



                </div>
            <?php } ?>

1 Ответ

0 голосов
/ 31 октября 2018

Вы должны изменить несколько функций, сначала нужно изменить функцию addtocart.

добавление Yii::$app->session['cart']['id'][] = $id;

...