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
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.
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.
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:
Hope I have revealed the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With