我正在尝试在学说中创建购物车。现在我被"数量"陷入困境。我正在尝试实现这一目标,如果产品已经在购物车中,请更新数量(数量 1)。
这是我的实体:
cart.php
class Cart
{
/**
* @ORMId
* @ORMGeneratedValue(strategy="UUID")
* @ORMColumn(type="guid")
*/
private $id;
/**
* @ORMOneToOne(targetEntity="Order", inversedBy="cart", cascade={"persist"})
* @ORMJoinColumn()
*/
private $order;
/**
* @ORMOneToMany(targetEntity="CartItem", mappedBy="cart", cascade={"persist"})
*/
private $cartItems;
public function __construct()
{
$this->cartItems = new ArrayCollection();
}
...
public function getItems()
{
return $this->cartItems;
}
public function addItem(CartItem $cartItem, Product $product, int $quantity = 1)
{
if ($this->cartItems->contains($cartItem))
return;
$cartItem->setProduct($product);
$cartItem->setQuantity($quantity);
$cartItem->setBoughtPrice($product->getBoughtPrice());
$cartItem->setPrice($product->getPrice());
$this->cartItems[] = $cartItem;
// set the *owning* side!
$cartItem->setCart($this);
}
public function removeItem(CartItem $cartItem)
{
$this->cartItems->removeElement($cartItem);
// set the owning side to null
$cartItem->setCart(null);
}
}
cartitem.php
class CartItem
{
/**
* @ORMId
* @ORMGeneratedValue(strategy="UUID")
* @ORMColumn(type="guid")
*/
private $id;
...
/**
* @ORMManyToOne(targetEntity="Cart", inversedBy="cartItems")
* @ORMJoinColumn(name="cart_id", referencedColumnName="id")
*/
private $cart;
/**
* @ORMManyToOne(targetEntity="AppEntityProductProduct", inversedBy="cartItems")
* @ORMJoinColumn(name="product_id", referencedColumnName="id")
*/
private $product;
public function getId()
{
return $this->id;
}
...
public function getCart()
{
return $this->cart;
}
public function setCart(Cart $cart)
{
$this->cart = $cart;
}
public function getProduct()
{
return $this->product;
}
public function setProduct(Product $product)
{
$this->product = $product;
}
...
}
我认为最重要的方法是 additem()在cart.php。
中是否可以访问相关实体的所有行并比较产品是否已经存在?
还是我应该在控制器中进行操作?
尝试以下代码:
public function addItem(CartItem $cartItem, Product $product, int $quantity = 1)
{
if ($this->cartItems->contains($cartItem))
return;
// Looking for an item with the same product
foreach ($this->cartItems as $item) {
// Suppose the product are equals comparing it by id
if ($item->getProduct()->getId() === $product->getId()) {
// We find an existing cart item for the product
// Update the cart item info:
$cartItem->setQuantity( $cartItem->getQuantity() + $quantity );
// NB: should we take care of the quantity ?
$cartItem->setBoughtPrice($cartItem->getBoughtPrice() + $product->getBoughtPrice());
// NB: should we take care of the quantity ?
$cartItem->setPrice($cartItem->getPrice() + $product->getPrice());
return;
}
}
$cartItem->setProduct($product);
$cartItem->setQuantity($quantity);
$cartItem->setBoughtPrice($product->getBoughtPrice());
$cartItem->setPrice($product->getPrice());
$this->cartItems[] = $cartItem;
// set the *owning* side!
$cartItem->setCart($this);
}
希望此帮助