检查产品是否已存在于购物车中 - Cakephp 3
Check if product already exists in the cart - Cakephp 3
朋友们,我有这个方法来检查购物车中是否已经存在该产品。同理,如果产品存在,他会添加更改数量,但他也会让产品重新发送。
.
.
$order = $this->Orders->newEntity();
if ( $this->request->is( 'post' ) ) {
$order = $this->Orders->patchEntity( $order, $this->request->getData() );
$order->order = $this->Orders->Products->get( $order->product_id, ['contain' => ['Users']] );
$session = $this->request->getSession();
$cart = $session->read( 'cart' );
$counter = 0;
foreach((array) $cart as $cartOne){
if($cartOne['product_id'] == $order->product_id){
$cartOne['quantity'] += 1;
$counter++;
break;
}
}
$cart[] = $order;
$session->write('cart', $cart);
谁能分析一下,不胜感激!我真的不会做这个过滤器。
您的 break
退出了 foreach
循环,但随后您将新订单附加到购物车 ($cart[] = $order
) 而没有检查 $counter
变量。您可能想先检查一下:
if (!$counter) {
$cart[] = $order;
}
朋友们,我有这个方法来检查购物车中是否已经存在该产品。同理,如果产品存在,他会添加更改数量,但他也会让产品重新发送。
.
.
$order = $this->Orders->newEntity();
if ( $this->request->is( 'post' ) ) {
$order = $this->Orders->patchEntity( $order, $this->request->getData() );
$order->order = $this->Orders->Products->get( $order->product_id, ['contain' => ['Users']] );
$session = $this->request->getSession();
$cart = $session->read( 'cart' );
$counter = 0;
foreach((array) $cart as $cartOne){
if($cartOne['product_id'] == $order->product_id){
$cartOne['quantity'] += 1;
$counter++;
break;
}
}
$cart[] = $order;
$session->write('cart', $cart);
谁能分析一下,不胜感激!我真的不会做这个过滤器。
您的 break
退出了 foreach
循环,但随后您将新订单附加到购物车 ($cart[] = $order
) 而没有检查 $counter
变量。您可能想先检查一下:
if (!$counter) {
$cart[] = $order;
}