Doctrine 2.x - isModified equivalent?
In Doctrine 1.x, there was an $entity->isModified() method, which happened to be quite useful. Has anyone found a way to replicate this functionality in Doctrine 2.x?
I've explored a few avenues, such as retrieving the UnitOfWork, asking it to compute changes for the entity in question, and then asking if if that entity is in the queue for changes, but all of these have caused nasty side-effects such as M2M relations getting inserted twice, causing a database constraint exceptio开发者_如何学Gon. I guess that means that this is "not the intended usage"!
It seems like a huge duplication of work to resort to keeping track of changes via another method when Doctrine is already keeping track, so I hope that there's a way.
I would like to see some code to understand how it's getting inserted twice. Also, why do you want to do this?
Anyway, you can consider changing your tracking policy. Sounds like your looking for the notify policy.
Else, you can always use the pre-update annotation if you can get away with it.
I recommend you do not use persist/all cascade in the assocations - you will get an exception then where you need to persist the associations first. Might help debugging with the double persist problem as well.
In our Doctrine 1.x based CMS, we would typically fetch the entity in question, populate it with data, and then ask $entity->isModified()? (And if not, we could send feedback to the user - "No changes")
Code-wise, the isModified() replacement is like so:
public function isModified($entity) {
$metadata = $this->em->getClassMetadata(get_class($entity));
$uow = $this->em->getUnitOfWork();
$uow->computeChangeSet($metadata, $entity);
return $uow->isEntityScheduled($entity);
}
Unfortunately, if we've added M2M relations, this causes the M2M to get added twice when persisting, probably due to the fact that Doctrine is then calling uow->computeChangeSets(), causing the M2M insert to be queued twice.
We have resorted to doing something similar to what is suggested in the notify tracking policy - essentially hooking all of our setters.
NOTE This answer was posted in question by OP Mark
精彩评论