How to formulate a database query to retrieve data from an intermediate table?
07:50 22 Aug 2026

We have 3 Entities:

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

    #[ORM\OneToMany(targetEntity: ProductOrder::class, mappedBy: 'order')]
    private Collection $productOrder;
}

#[ORM\Table(name: '`storage_products`')]
#[ORM\Entity(repositoryClass: ProductRepository::class)]
class Product
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private int $id;

    #[ORM\OneToMany(targetEntity: ProductOrder::class, mappedBy: 'product')]
    private Collection $productOrders;
}

#[ORM\Table(name: '`storage_product_orders`')]
#[ORM\Entity(repositoryClass: ProductOrderRepository::class)]
class ProductOrder
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private int $id;

    #[ORM\ManyToOne(targetEntity: Product::class, inversedBy: 'product_orders')]
    #[ORM\JoinColumn(name: '`product_id`', referencedColumnName: '`id`', nullable: false)]
    private Product $product;

    #[ORM\ManyToOne(targetEntity: Order::class, inversedBy: 'product_orders')]
    #[ORM\JoinColumn(name: '`order_id`', referencedColumnName: '`id`', nullable: false)]
    private Order $transaction;

    #[ORM\Column(type: 'integer')]
    private int $count;
}

How to formulate a query to select 1 entity Order by ID with the products field, which will contain a collection of entity Product, the count field of which will hold the value from the count field of entity ProductOrder?

public function findOneById(int $id): ?Order
{
    $queryBuilder = $this->getEntityManager()->createQueryBuilder();

    $order = $queryBuilder->select('o')
        ->from(Order::class, 'o')
        ->where('o.id = :o_id')
        ->join(...)
        ->join(...)
        ->setParameter('o_id', $id)
        ->getQuery()
        ->getOneOrNullResult();

    return $order;
}
sql postgresql symfony orm doctrine