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.