Doctrine's Object Relational Mapper and the Entity classes provide us developers a very easy way to deal with Table associations. When we define a One To Many / Many To One Table association, the best way to query results is from the One To Many side.

Before you continue reading, you may want to check on this previous posts:

 

Lets suppose you have a Customers Entity. Each Customer has many bills associated to it:

...

    /**
     * @var bool
     *
     * @ORM\Column(name="is_active", type="boolean", nullable=false)
     */
    private $isActive= false;
    
    /**
     * @ORM\OneToMany(targetEntity="Billing", mappedBy="customers", cascade={"persist", "remove"})
     */
    private $billing;
    
    /**
     *
     */
    public function __construct()
    {
        $this->billing = new ArrayCollection();
    }


...

 

The default Sorting Order is Ascending by the Primary Key that is Id in the Billing Entity, but if you want this Collection of Billing to be sorted by different column other than the Primary Key, we just need to put this OrderBy Annotation:

...
    
    /**
     * @ORM\OneToMany(targetEntity="Billing", mappedBy="customers", cascade={"persist", "remove"})
     * @ORM\OrderBy({"createdDate" = "DESC"})
     */
    private $billing;
    
    /**
     *
     */
    public function __construct()
    {
        $this->billing = new ArrayCollection();
    }

...

 

This annotation also works for Many To Many relation:

...

    /**
     * @ManyToMany(targetEntity="Group")
     * @OrderBy({"name" = "DESC"})
     */
    private Collection $groups;

...

 

This way, you will get a Customer with its associated Bills sorted by Descending Order in the "created_date" column. This annotation is very powerful and prevents you from writing a custom DQL or SQL query or implementing custom PHP code to sort this data, saving you hours of development time.

Also, if later you need to sort by a different column, its very easy to do this just need to change the name of the column in this annotation.

 

More on this refer to the Doctrine Project Web site