如何在 Doctrine 中附加分离的实体?

Čam*_*amo 6 entity unit-of-work entitymanager detach doctrine-orm

我有一个脚本将循环中的一些“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;
}
Run Code Online (Sandbox Code Playgroud)

我试过了,$this->em->persist($B)但它使我在数据库中重复了 $B。这意味着 DB 中的新 B 项目(带有新 ID)而不是在 A 和 B 之间创建连接。我也尝试过,$this->em->merge($B)但它抛出了一个异常“通过关系 'App\Model\Entity\A#B' 找到了一个新实体未配置为级联持久操作”。如何处理这个问题?

非常感谢。

Čam*_*amo 7

因此,在这种情况下,如果某些内容像 $B 实体一样合并,则有必要通过 = 运算符对其进行分配。因为 merge() 返回实体。它不影响原始实体。

catch( \Exception $e )
{
    ...
    $B = $this->em->merge( $B );
}
Run Code Online (Sandbox Code Playgroud)

  • 现在合并已被弃用,该怎么办? (3认同)