【发布时间】:2016-06-25 19:29:13
【问题描述】:
我有一个脚本,它将循环中的一些“A”类型的新实体保存到数据库中。但是循环可能会抛出一些关闭 entityManager 的异常。所以必须重新开放。它导致应该与每个“A”实体连接的另一个类型“B”的实体与 unitOfWork 分离。如何将“B”附加到 unitOfWork?这是一个例子:
public function insert( Array $items )
{
$B = $this->bRepository->findOneBy( ['name' => 'blog'] );
$result = [ 'errors' => [], 'saved_items' => [] ];
foreach( $items as $item )
{
try
{
$A = new Entity\A();
$A->create([
'name' => $item->name,
'B' => $B // Here is the problem after exception. $B is detached.
]);
$this->em->persist( $A );
$this->em->flush( $A );
$result['saved_items'][] = $item->name;
} catch( \Eception $e )
{
$result['errors'][] = 'Item ' . $item->name . ' was not saved.';
$this->em = $this->em->create( $this->em->getConnection(), $this->em->getConfiguration() );
}
}
return $result;
}
我尝试了$this->em->persist($B),但它使我在数据库中重复了 $B。这意味着 DB 中的新 B 项(具有新 id)而不是在 A 和 B 之间创建连接。我也尝试过 $this->em->merge($B) 但它抛出异常“通过关系找到了一个新实体 'App\Model\Entity\A# B' 未配置为级联持久操作”。如何处理这个问题?
非常感谢。
【问题讨论】:
标签: doctrine-orm entity entitymanager unit-of-work detach