You can use native shuffling (if you don't use KnpPaginator
):
$entries = $contest->getEntries()->toArray();
shuffle($entries);
Also if you need all entities you can write:
$entriesCollection = $contest->getEntries();
if ($entriesCollection instanceof PersistentCollection) {
$entriesCollection->initialize();
}
$entries = $entriesCollection->toArray();
shuffle($entries);
Alternatively you can dig to @ORM\OrderBy
and custom DQL functions to use SQL ORDER BY RAND()
. Also this approach would work better with KnpPaginator
In response to comment:
Doctrine mostly uses proxies on your classes instead of directly use them, because of lazy loading and optimization purposes, also doctrine has abstraction over basic arrays implementing own Collection
interface that has some useful methods like map
, exist
and so on. PersistentCollection
is proxy (lazy) collection implementing Collection
interface it can be returned if you just requested some object from repository and trying to use some field that uses an array of objects so in some cases (like that) it's better to force loading of objects via initialize
method (don't worry it won't load them twice). Also all objects requested from repository are not your classes they are just proxies extending your entities and implementing Proxy
interface so be careful! If something gone wrong in your database layer try to add the following:
if ($yourEntityLoadedFromSomeWhere instanceof Proxy) {
$yourEntityLoadedFromSomeWhere->__load();
}
getEntries
? If it's anArrayCollection
, you could simply use$entries = $contest->getEntries()->toArray();
and simplyshuffle($entries);
without the loop \$\endgroup\$