Symfony ManyToMany如何获取与另一个对象相关的对象



我不明白如何访问与CartLine相关的产品。

我有两个实体

购物车实体:

/**
* @ORMManyToMany(targetEntity="AppEntityProduct", inversedBy="cartLines")
* @ORMJoinTable(name="cart_line_product")
*/
private $product;
public function __construct()
{
$this->product = new ArrayCollection();
}
/**
* @return Collection|Product[]
*/
public function getProduct(): Collection
{
return $this->product;
}

产品实体:

/**
* @ORMManyToMany(targetEntity="AppEntityCartLine", mappedBy="product")
*/
private $cartLines;
public function __construct()
{
$this->cartLines = new ArrayCollection();
}
/**
* @return Collection|CartLine[]
*/
public function getCartLines(): Collection
{
return $this->cartLines;
}

接下来,我通过表单将产品添加到购物篮中,如下所示:

if ($form->isSubmitted() && $form->isValid()) {
$cartLine = new CartLine();
$cartLine->addProduct($product);
$em->persist($cartLine);
$em->flush();

产品按预期添加。

然后我尝试在购物篮中展示产品:

$id = $this->getUser()->getCart()->getId();
$cartline = $cartLineRepo->findAllCartLineByUser($id);

然后在模板中

{% for cart in cartline.id %} //OR {% for cart in cartline.product.id %}
<div class="item">
</div>
{% endfor %}

我收到错误Key "id" for array with keys "0, 1, 2, 3" does not exist

或控制器中的调用

$cart = $this->getDoctrine()->getRepository(CartLine::class)->findAll();
foreach ($cart as $value){
$id = $value->getProduct()->getId();
}

我收到一个错误Attempted to call an undefined method named "getId" of class "DoctrineORMPersistentCollection".

如何获取相关对象或如何修复它?

您在这里有ManyToMany关系,而不是ManyToOne(一个产品有多个购物车(

因此,$value->getProduct()返回一个ArrayCollection,而不是单个product
这就是为什么getId()不起作用的原因,因为它不是一个product的对象。

我感觉你更需要ManyToOne <=> OneToMany关系而不是ManyToMany

如果你确定你需要一个ManyToMany关系,那么这就是你的代码应该如何

$cartLines=$this->getDoctrine()->getRepository(CartLine::class)->findAll();
foreach($cartLines as $cartLine) {
$products=$cartLine->getProduct(); //ArrayCollection
foreach($products as $product) {
$id=$product->getId();
}
}

最新更新