【问题标题】:How to attache detached entity in Doctrine?如何在 Doctrine 中附加分离的实体?
【发布时间】: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


    【解决方案1】:

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

    catch( \Exception $e )
    {
        ...
        $B = $this->em->merge( $B );
    }
    

    【讨论】:

    • 合并被弃用了怎么办?
    • 不使用Doctrine?只是开玩笑。对不起,我不知道。我暂时没有接触 Doctrine。
    猜你喜欢
    • 2014-06-20
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    相关资源
    最近更新 更多