In various cases I need to sort a Doctrine\Common\Collections\ArrayCollection
according to a property in the object. Without finding a method doing that right away, I do this:
// $collection instanceof Doctrine\Common\Collections\ArrayCollection
$array = $collection->getValues();
usort($array, function($a, $b){
return ($a->getProperty() < $b->getProperty()) ? -1 : 1 ;
});
$collection->clear();
foreach ($array as $item) {
$collection->add($item);
}
I presume this is not the best way when you have to copy everything to native PHP array and back. I wonder if there is a better way to "usort" a Doctrine\Common\Collections\ArrayCollection
. Do I miss any doc?
If you have an ArrayCollection field you could order with annotations. eg:
Say an Entity named Society has many Licenses. You could use
That will order the ArrayCollection by endDate (datetime field) in desc order.
See Doctrine documentation: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html#orderby
Since Doctrine 2.3 you can use the Criteria API
Eg:
To sort an existing Collection you are looking for the ArrayCollection::getIterator() method which returns an ArrayIterator. example:
The easiest way would be letting the query in the repository handle your sorting.
Imagine you have a SuperEntity with a ManyToMany relationship with Category entities.
Then for instance creating a repository method like this:
... makes sorting pretty easy.
Hope that helps.