Symfony ManyToMany how fetch object related to another object

I don’t understand how to access Product related to CartLine.

I have two entities

CartLine entity:

  /**
     * @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;
    }

Product entity:

    /**
     * @ORMManyToMany(targetEntity="AppEntityCartLine", mappedBy="product")
     */
    private $cartLines;

    public function __construct()
    {
        $this->cartLines = new ArrayCollection();
    }
    /**
     * @return Collection|CartLine[]
     */
    public function getCartLines(): Collection
    {
        return $this->cartLines;
    }

Next, I add the product to the basket through the form, like this:

if ($form->isSubmitted() && $form->isValid()) {

            $cartLine = new CartLine();
            $cartLine->addProduct($product);

            $em->persist($cartLine);
            $em->flush();

Product is added as expected.

Then I try to display the products in the basket:

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

then in template

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

I get an error
Key "id" for array with keys "0, 1, 2, 3" does not exist

Or a call in the controller

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

I get an error Attempted to call an undefined method named "getId" of class "DoctrineORMPersistentCollection".

How can I get a related object or how to fix it?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *