Persist () and flush () inside a loop - Doctrine

I want to know how many times the ff: codes will make a circular trip to the database.

foreach ($recipients as $recipient) { $received_email = new ReceivedEmail(); $received_email->setRecipient($recipient); $received_email->setEmail($email); $entityManager->persist($received_email); $entityManager->flush(); } 

$recipients is an array of User objects with a one-to-many relationship with ReceivedEmail

$email is a one-to-many object with ReceivedEmail.

If, for example, $recipients has five entities, does the loop generate a total of five attempts to access the database? Or just one?

Is the above example the most optimized way to insert new ReceivedEmail entries?

thanks

+4
source share
1 answer

One INSERT statement will be created for each save.

Alternatively, you can simply display your SQL queries for debugging, just configure Doctrine for logging: fooobar.com/questions/233368 / ...

In your case:

 $entityManager->getConfiguration()-> setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger()); 

For many inserts, you should consider batch processing :

Hope I found a problem.

+10
source

All Articles