blog.iwanluijks.nl
IL
Blog post

Efficient Doctrine entity iteration

By Iwan Luijks · · Back to blog


There are a ton of ways described online to iterate entities efficiently in Doctrine 2.* (up to at least 2.17), but the most efficient one is definitely to lookup entities using your own for loop.

<?php
    ...

    $maxLimit = 100_000;
    $limit = 200;
    $offset = 0;

    for ($offset = 0; $offset < $maxLimit; $offset += $limit) {
        $myEntities = $myEntityRepository->findBy(['myField' => true], ['fieldToOrderBy' => 'ASC'], $limit, $offset);

        if (!$myEntities) {
            break;
        }

        /** @var MyEntity $myEntity */
        foreach ($myEntities as $myEntity) {
    	// ... do something
        }

        // Optionally call `$entityManager->clear();` here.
        // $entityManager->clear();
    }

    ...

This article was updated on . Labeled under: php, doctrine.