Cannot access $items collection in class order

Viewed 41

I'm trying to display orders and order items in view like below but the result is an empty collection.

Result from Dump(order.getItems)

Controller:


<?php

namespace App\Controller;

use App\Repository\OrderRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class MyController extends AbstractController
{
    #[Route('/all', name: 'app_index')]
    public function index(OrderRepository $orderRepository): Response
    {
        return $this->render('/index.html.twig', [
            'orders' => $orderRepository->findAll()
        ]);
    }
}

Twig:

{% for order in orders %}
   {{ dump(order.getItems()) }}
{% endfor %}

I have class Order mapped by orderRef in OrderItem class. The mapping is inversed by the "items" collection in Order class.

Order entity:

<?php

namespace App\Entity;

use App\Repository\OrderRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: OrderRepository::class)]
#[ORM\Table(name: '`order`')]
class Order
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\OneToMany(mappedBy: 'orderRef', targetEntity: OrderItem::class, orphanRemoval: true)]
    private Collection $items;

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

    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * @return Collection<int, OrderItem>
     */
    public function getItems(): Collection
    {
        return $this->items;
    }
}

OrderItem entity:

<?php

namespace App\Entity;

use App\Repository\OrderItemRepository;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: OrderItemRepository::class)]
class OrderItem
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\ManyToOne(inversedBy: 'items')]
    #[ORM\JoinColumn(nullable: false)]
    private ?Order $orderRef = null;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getOrderRef(): ?Order
    {
        return $this->orderRef;
    }

    public function setOrderRef(?Order $orderRef): self
    {
        $this->orderRef = $orderRef;

        return $this;
    }
}

1 Answers

Instead of a findAll() you can call a new query builder in your repository with an orderBy

public function getSortedOrders() 
{ 
    $qb = $this->createQueryBuilder('o')
        ->orderBy('o.orderRef', 'DESC');

    return $qb->getQuery()->getResult(); 
}```
Related