Fixing detatched Doctrine entity problems

I’m not sure WHY it happens, but sometimes Doctrine entities can become detatched from the entity manager (If anyone does, please comment below!).

If you’ve ever added an existing object to a new one and tried to persist, you may see this error:

[Doctrine\ORM\ORMInvalidArgumentException]
A new entity was found through the relationship ‘OAuth\Client#user’ that was not configured to cascade persist operations for entity: OAuth\OAuthUser@000
000007e2d73fd0000000054f34ea6. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist t
his association in the mapping for example @ManyToOne(..,cascade={“persist”}). If you cannot find out which entity causes the problem implement ‘OAuth\OA
uthUser#__toString()’ to get a clue.

In the case of my code above, the user entity had become detached somehow. Previously, I had managed to solve this problem by calling merge($entity) instead of persist($entity), but this is itself causes problems. If you have join column collections, these will no longer persist!

Therefore the answer is to re-attach the entity first!

public function create(Client $client)
{
$em = $this->getEntityManager();
$user = $client->getUser();
if ($em->getUnitOfWork()->getEntityState($user) !== UnitOfWork::STATE_MANAGED) {
$user = $em->merge($user);
$client->setUser($user);
}
$em->persist($client);
$em->flush();
return $client;
}