Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

persist() and flush() inside loop - Doctrine

I want to know how many times the ff: codes will make a roundway 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 One-to-Many relationship with ReceivedEmail

$email is an object with One-to-Many relationship with ReceivedEmail.

If for instance $recipients has five entities, does the loop generates a total of five trips to database? Or only one?

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

Thanks

like image 229
Edville Avatar asked Apr 18 '13 11:04

Edville


People also ask

What is persist flush?

Persist and Flush​ flush() . em. persist(entity) is used to mark new entities for future persisting. It will make the entity managed by given EntityManager and once flush will be called, it will be written to the database.

What is a repository doctrine?

It means the place where our data can be accessed from, a repository of data. This is to distinguish it from a database as a repository does not care how its data is stored.


1 Answers

There will be generated one INSERT statement for each persist.

What is more, you can just display yours SQL statements for debug, just configure Doctrine for logging: https://stackoverflow.com/a/4585421/1815881

In your case:

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

For many inserts you should consider the batch prcessing:

  • https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/batch-processing.html

Hope I have revealed the problem.

like image 138
Athlan Avatar answered Oct 16 '22 03:10

Athlan