I'm trying to create cart in doctrine. Now I'm stuck with "quantity". I'm trying to achieve that if product is already in cart, update quantity(quantity + 1).
Here are my entities:
Cart.php
class Cart
{
/**
* @ORM\Id
* @ORM\GeneratedValue(strategy="UUID")
* @ORM\Column(type="guid")
*/
private $id;
/**
* @ORM\OneToOne(targetEntity="Order", inversedBy="cart", cascade={"persist"})
* @ORM\JoinColumn()
*/
private $order;
/**
* @ORM\OneToMany(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
{
/**
* @ORM\Id
* @ORM\GeneratedValue(strategy="UUID")
* @ORM\Column(type="guid")
*/
private $id;
...
/**
* @ORM\ManyToOne(targetEntity="Cart", inversedBy="cartItems")
* @ORM\JoinColumn(name="cart_id", referencedColumnName="id")
*/
private $cart;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Product\Product", inversedBy="cartItems")
* @ORM\JoinColumn(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;
}
...
}
I think most important method is addItem() in Cart.php.
Is it possible to access all rows from related entity and compare if product already exist?
Or should I do it in the controller?