Created
April 3, 2012 16:53
-
-
Save marijn/2293613 to your computer and use it in GitHub Desktop.
An example on sorting Doctrine\Common\Collection\ArrayCollection elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$collection = new Doctrine\Common\Collection\ArrayCollection(); | |
// add objects to the collection that contain a getCreated method returning a DateTime instance | |
$iterator = $collection->getIterator(); | |
$iterator->uasort(function ($first, $second) { | |
if ($first === $second) { | |
return 0; | |
} | |
return (float) $first->getCreated()->format("U.u") < (float) $second->getCreated()->format("U.u") ? -1 : 1; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Better late than never... This may be of use to someone else.
Thanks for the above advice. I put it in a
PostLoad
life-cycle callback so this is done implicitly after the entity is loaded. Obviously you wouldn't need anOrderBy
at all as the sort logic is just being shifted from SQL to PHP.In my case I have a bunch of "thing", of which is many-to-many with
Region
. There is aThingRegion
entity sitting between the two with independent properties about their relationship, so my link is really one-to-many-to-one rather than a logical many-to-many.I needed the regions to be sorted by name from the thing perspective, so did this in the
Thing
class:Afterwhich
getThingRegions()
returns a collection sorted as intended. You could also addPrePersist
andPreUpdate
life-cycle callbacks if you want the sort to happen just before saving, if that matters.(Name of "Thing" obscured to protect client identity.)