"usort" Doctrine \ Common \ Collections \ ArrayCollection?

In different cases, I need to sort Doctrine\Common\Collections\ArrayCollection according to the property of the object. Not finding a method that does this 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 guess this is not the best way when you need to copy everything into your own PHP array and vice versa. I wonder if there is a better way to "usort" a Doctrine\Common\Collections\ArrayCollection . Am I missing a document?

+27
php doctrine2
May 23 '13 at 3:56
source share
3 answers

To sort an existing collection, you are looking for the ArrayCollection :: getIterator () method, which returns an ArrayIterator. Example:

 $iterator = $collection->getIterator(); $iterator->uasort(function ($a, $b) { return ($a->getPropery() < $b->getProperty()) ? -1 : 1; }); $collection = new ArrayCollection(iterator_to_array($iterator)); 

The easiest way is to allow the request in the repository to process your sort.

Imagine you have a SuperEntity with a ManyToMany relationship with Category objects.

Then, for example, by creating such a repository method:

 // Vendor/YourBundle/Entity/SuperEntityRepository.php public function findByCategoryAndOrderByName($category) { return $this->createQueryBuilder('e') ->where('e.category = :category') ->setParameter('category', $category) ->orderBy('e.name', 'ASC') ->getQuery() ->getResult() ; } 

... makes sorting easy.

Hope this helps.

+65
May 23 '13 at 7:08
source share

Starting with Doctrine 2.3 you can use the criteria API

For example:

 <?php public function getSortedComments() { $criteria = Criteria::create() ->orderBy(array("created_at" => Criteria::ASC)); return $this->comments->matching($criteria); } 

Note. This solution requires public access to the $createdAt property or the public getter method getCreatedAt() .

+34
Jun 16 '14 at
source share

If you have an ArrayCollection field, you can order annotations. eg:

Say that an organization named Society has many Licenses. you can use

 /** * @ORM\OneToMany(targetEntity="License", mappedBy="society") * @ORM\OrderBy({"endDate" = "DESC"}) **/ private $licenses; 

This will arrange the ArrayCollection by endDate (datetime field) in desc order.

See the Doctrine documentation: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html#orderby

+10
Oct 29 '15 at 10:15
source share



All Articles