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

问题描述 投票:0回答:1

我不知道如何访问与CartLine相关的产品。

我有两个实体

CartLine实体:

  /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Product", inversedBy="cartLines")
     * @ORM\JoinTable(name="cart_line_product")
     */
    private $product;

    public function __construct()
    {
        $this->product = new ArrayCollection();
    }

    /**
     * @return Collection|Product[]
     */
    public function getProduct(): Collection
    {
        return $this->product;
    }

产品实体:

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\CartLine", 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 "Doctrine\ORM\PersistentCollection".

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

php symfony doctrine foreign-keys many-to-many
1个回答
0
投票

您在这里有一个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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.