0

我正在使用 CakePHP 3.2 并构建一个购物车。

我正在使用Cookie组件将产品存储在购物车中。

这就是我将产品添加到购物车的操作

public function addToCart()
    {
      $this->loadModel('Products');

      if ($this->request->is('post')) {
        $p_id = $this->request->data('product_id');
        $p_quantity = $this->request->data('qnty');

        $product = $this->Products->get($p_id);

        if (!$product) {
          throw new NotFoundException(__('Invalid Product'));
        }

          $this->Cookie->write('Cart',
            ['id' => $p_id, 'quantity' => $p_quantity]);

          $itemsCount = count($this->Cookie->read('Cart'));

          $this->Flash->success(__('Product added to cart'));
          return $this->redirect($this->referer());

      }
    }

我怎么能在 Cookie 中添加多维数组,因为购物车可以有多个产品,每个产品都有多个值。view另外,我如何打印cart()方法?

我的cart()方法是这样的

public function cart()
    {
      $cart_products = $this->Cookie->read('Cart');

      $this->set('cart_products', $cart_products);
    }

并打印为

foreach($cart_products as $c_product):
  echo $c_product->id.' : '.$c_product->quantity;   // line 45
endforeach;

但这给出了错误

Trying to get property of non-object [ROOT/plugins/ArgoSystems02/src/Template/Orders/cart.ctp, line 45]
4

2 回答 2

1

您将数组写入 cookie:

$this->Cookie->write('Cart', ['id' => $p_id, 'quantity' => $p_quantity]);

我相信您想要的是将所有产品存储在 cookie 中:

$cart = $this->Cookie->read('Cart') ? $this->Cookie->read('Cart') : [];
$cart[] = $product;
$this->Cookie->write('Cart', $cart)
于 2016-07-13T06:58:00.330 回答
1

尝试以下

代替方法

$this->Cookie->write('Cart',['id' => $p_id, 'quantity' => $p_quantity]);

进入

$cart = [];
if($this->Cookie->check('Cart')){
    $cart = $this->Cookie->read('Cart');
}
$cart[] = ['id' => $p_id, 'quantity' => $p_quantity];//multiple
$this->Cookie->write('Cart', $cart);

而不是视图

foreach($cart_products as $c_product):
  echo $c_product->id.' : '.$c_product->quantity;   // line 45
endforeach;

进入

foreach($cart_products as $c_product):
  echo $c_product['id'].' : '.$c_product['quantity'];   // line 45
endforeach;
于 2016-07-13T07:13:10.957 回答