Softdeletable behaviour and really deleting the entity
I'm using DoctrineExtensions with StofDoctrineExtensionsBundle to get the soft-deleteable behaviour.
It works really well in the frontend of my application.
In the backend i need the option to "hard" delete entities.
I have disabled the filter in my admin controllers (i use SonataAdmin):
$filters = $this->getModelManager()->getEntityManager($this->getClass())->getFilters();
if (array_key_exists('softdeleteable', $filters->getEnabledFilters())) {
$filters->disable('softdeleteable');
}
This works (soft deleted entities show up in the lists), but when i try to delete it, the entity does get soft-deleted again. How can i force a "hard" delete?
You don't need to disable filter - it just used for filtering records on select. You must disable listener instead:
// $em is your EntityManager
foreach ($em->getEventManager()->getListeners() as $eventName => $listeners) {
foreach ($listeners as $listener) {
if ($listener instanceof GedmoSoftDeleteableSoftDeleteableListener) {
$em->getEventManager()->removeEventListener($eventName, $listener);
}
}
}
and then call
$em->remove($entity);
$em->flush();
No need to create a listener or anything to HARD delete with softdeleteable enabled.
the original softdeleteable event has this line:
$reflProp = $meta->getReflectionProperty($config['fieldName']);
$oldValue = $reflProp->getValue($object);
if ($oldValue instanceof Datetime) {
continue; // want to hard delete
}
All this mean if you:
$entity->setDeletedAt(new Datetime());
$em->flush();
And then:
$em->remove($entity);
$em->flush();
At that point it will be hard deleted.
If you allready have a valid date inside deletedAt field when you call ->flush() after a ->remove($entity) your entity will be hard deleted
不是最优雅的方式:你总是可以用SQL进行真正的删除,它将绕过软删除
$em->createQuery("DELETE MyEntity e WHERE e = :et")->setParameter('et',$entity)->execute();
链接地址: http://www.djcxy.com/p/65028.html