How to attache detached entity in Doctrine?
Asked Answered
S

1

6

I have a script which saves some new entities of type "A" in the loop to the database. But the loop can throw some exceptions which close entityManager. So it must be reopen. It causes that another entity of type "B" which should be joined with every "A" entity is detached from unitOfWork. How can I attache "B" to unitOfWork? This is an example:

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;
}

I tried $this->em->persist($B) but it makes me a duplicates of $B in database. It means new B items in DB(with new ids) instead of creating join between A and B. I also tried $this->em->merge($B) but it throws an exception "A new entity was found through the relationship 'App\Model\Entity\A#B' that was not configured to cascade persist operations". How to handle this issue?

Thanks a lot.

Strongwilled answered 10/3, 2016 at 19:11 Comment(0)
S
7

So it seems if something is merged like $B entity in this case, it is necessary to assign it via = operator. Because merge() RETURNS entity. It does not affect original entity.

catch( \Exception $e )
{
    ...
    $B = $this->em->merge( $B );
}
Strongwilled answered 11/3, 2016 at 0:8 Comment(3)
What do do now that merge is deprecated?Gowen
Not to use Doctrine? Just joking. Sorry I dont know. I am not in touch with Doctrine for now.Cereal
@DavideCasiraghi I suppose we can still use merge according to the documentation of version 2.14Zerelda

© 2022 - 2024 — McMap. All rights reserved.