我有一个Cart
实体,其中包含ArrayCollection
的{{1}}。代码中的关系-
Cart.php:
CartItems
class Cart
{
/**
* @ORM\OneToMany(targetEntity="CartItem", mappedBy="cart")
*/
private $cartItems;
public function __construct(User $user)
{
$this->cartItems = new ArrayCollection();
}
}
本质上是指向CartItems
实体的DB指针(由于缺少更好的术语),带有一个附加的Product
字段。
CartItem.php:
quantity
在我的应用中,当用户想要向其class CartItem
{
/**
* @ORM\ManyToOne(targetEntity="Cart", inversedBy="cartItems")
*/
private $cart;
/**
* @ORM\OneToOne(targetEntity="Product")
*/
private $product;
/**
* @ORM\Column(type="float")
*
* @Assert\NotBlank(message="You must specify how much of the item you wish to buy")
* @Assert\Regex(pattern="/^\d+(\.\d{1,2})?$/", message="The quantity must be a number")
*/
private $quantity;
}
添加Product
时,我想检查该特定Cart
是否已经是{{1}之一}。如果是这样,我要增加Product
,否则将其添加到集合中。我不确定如何执行此操作。
CartItems
方法quantity
和ArrayCollection
仅返回true / false。有了我的设置,我不确定我将使用什么作为收藏的钥匙。
有什么建议吗?
答案 0 :(得分:1)
您可以为新的CartItems
过滤Product
。如果过滤后的CartItems
不为空,请增加quantity
,否则添加新的CartItem。
$newProduct // Product Object
$cartItems = $cart->getCartItems()->filter(function(CartItem $cartItem) (use $newProduct) {
return $cartItem->getProduct() === $newProduct;
});
if ($cartItems->count()) {
foreach ($cartItems as $cartItem) {
$cartItem->setQuantity($cartItem->getQuantity() + 1);
}
} else {
$cart->addCartItem(
(new CartItem())
->setProduct($newProduct)
->setQuantity(1)
);
}