5

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

oradwell
  • 392
  • 1
  • 12
Edville
  • 345
  • 1
  • 5
  • 18

1 Answers1

11

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.

Sree Menon
  • 28
  • 5
Athlan
  • 6,389
  • 4
  • 38
  • 56
  • Thanks. I guess I would just use nativeSQL for inserting multiple ReceivedEmail in my example so as to minimize the number of database trips – Edville Apr 18 '13 at 22:22
  • 1
    @Athlan, you did not specify what exactly `flush` does. – craned Jan 13 '16 at 23:14
  • An `insert` statement for each `persist` does not mean that it will create a new record for each `persist`. It will check to see if the object being `persisted` already exists, meaning that you have to create a new object for each `persist`. – craned Jan 29 '16 at 16:02