我有一个脚本,它将循环中一些类型为"A"的新实体保存到数据库中。但是循环可能会引发一些关闭实体管理器的异常。所以它必须重新开放。它导致应与每个"A"实体联接的另一个类型为"B"的实体从 unitOfWork 分离。如何将"B"附加到工作单元?这是一个示例:
public function insert( Array $items )
{
$B = $this->bRepository->findOneBy( ['name' => 'blog'] );
$result = [ 'errors' => [], 'saved_items' => [] ];
foreach( $items as $item )
{
try
{
$A = new EntityA();
$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的副本。这意味着数据库中的新 B 项(具有新 ID),而不是在 A 和 B 之间创建连接。我也尝试了$this->em->merge($B)
但它抛出了一个异常"通过关系'App\Model\Entity\A#B'找到一个新实体,该实体未配置为级联持久操作"。如何处理这个问题?
多谢。
因此,如果在这种情况下像实体$B合并某些内容,则有必要通过 = 运算符分配它。因为 merge() 返回实体。它不会影响原始实体。
catch( Exception $e )
{
...
$B = $this->em->merge( $B );
}