简体   繁体   中英

Doctrine 2 creating multiple records

I am trying to create multiple records via Doctrine, and I am running into a strange problem where it will create the first record successfully, but no others. Say I have the following where Record is a Doctrine Entity and record_id is the primary key:

 $entityManager->getConnection()->beginTransaction();

 foreach($recordsToCreate as $data)
 {
   $record = new Record();
   $record->field1 = $data['field1'];
   $record->field2 = $data['field2'];

   $entityManager->persist($record);
   $entityManager->flush();
 }

 $entityManager->getConnection()->commit();

If I have three records, the first will be created correctly, but not the other two. No errors or exceptions are thrown, but the records are not being created in the database. If I output each record after the flush, all fields are set correctly but the primary key is null after the first record. I'm thinking this is a Doctrine glitch but I want to make sure before I submit a bug report.

Thanks.

Figured it out-the answer wasn't putting flush() outside the loop as stated above. The solution was to use detach() after committing the transaction. So:

 foreach($recordsToCreate as $data)
 {
   $entityManager->getConnection()->beginTransaction();
   $record = new Record();
   $record->field1 = $data['field1'];
   $record->field2 = $data['field2'];

   $entityManager->persist($record);
   $entityManager->flush();

   $entityManager->getConnection()->commit();
   $entityManager->detach($record);
 }

That works for me now. The problem was that somehow (I think) the entity manager couldn't tell the difference between the first record and the rest, so detach ensures that it always has a new record when it's doing a create. Also, the transaction is in the loop now since I'm actually creating/modifying other records with this one in my actual code, so having it inside the loop is more accurate to my setup.

so In a nutshell, call detach on the new record after the commit and it's all good for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM