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

Updating a forked GitHub Repo

At the PHPNW 2014 conference, they had a ‘Hackathon’, where everyone got together and started hacking away at projects. I had a shot at the JoindIn website.

Anyway, I forked the repositories so I could work on my own branch. Now though, my fork is outdated, and needs updating. So in order to remedy this, we add another remote.

From your local machine’s cloned repo, you simply say:

git remote add upstream https://github.com/joindin/joindin-web2.git
git checkout master
git pull upstream master
git push origin master

Thanks to Derick Rethans of XDebug fame for this info 😀