Doctrine2 $em->persist($entity) on foreach loop

From the Doctrine documentation, it says that inserts are best performed with batch. And its a development of @AlterPHP ‘s answer.

You could use :

$batchSize = 20;

for ($i = 1; $i <= 10000; ++$i) {

    $car = new Car();
    // ... set number of wheels, but should always be to 4 right ?

    $em->persist($car);

    if (($i % $batchSize) === 0) {
        $em->flush();
        $em->clear(Car::class); // Detaches all Car objects from Doctrine!
    }
}

$em->flush(); // Persist objects that did not make up an entire batch
$em->clear(Car::class);

PS: i just read that from Doctrine 13.1. Bulk Inserts section. Now all you’ll need is a bigger parking !

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)