简体   繁体   English

教义2创建多个记录

[英]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. 我试图通过Doctrine创建多个记录,但遇到一个奇怪的问题,它将成功创建第一个记录,但没有其他记录。 Say I have the following where Record is a Doctrine Entity and record_id is the primary key: 说我有以下内容,其中Record是一个Doctrine实体,而record_id是主键:

 $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. 如果在刷新后输出每条记录,则所有字段均已正确设置,但第一条记录后主键为null。 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. 弄清楚了-答案不是如上所述将flush()放在循环之外。 The solution was to use detach() after committing the transaction. 解决方案是在提交事务后使用detach()。 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. 简而言之,在提交后在新记录上调用detach,这对我来说都是有好处的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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