问题描述
为Doctrine 2安装和使用SoftDeleteable行为扩展是非常容易的。问题通常是尝试禁用它的一些代码部分,并重新启用。您可能要这样做:
Installing and using SoftDeleteable behavior extension for Doctrine 2 is quite easy. The problem usually is trying to disable it for some code part and enabling again. You may want to do this to:
- 软删除的加载实体
- 删除实体从数据库完全绕过软删除过滤器
那么如何禁用它?
推荐答案
1。如何加载软删除的实体
根据文档,禁用实体管理器的过滤器:
1. How to load soft-deleted entity
As per the documentation, disable filter for entity manager:
$em->getFilters()->disable('softdeleteable');
$object = $em->find('AppBundle:Object', 1); // soft-deleted entity will be loaded
要再次启用软删除:
$em->getFilters()->enable('softdeleteable');
注意: $ em-> clear(); $ c如果实体已经加载了禁用的软删除过滤器,则可能需要$ c>。
尽管文档中没有提到,但如果您需要删除实体并绕过软删除过滤器,则第一个解决方案不起作用。过滤器需要从实体管理器的事件监听器中删除:
Even though it is not mentioned in documentation, the first solution does not work if you need to remove entity and bypass soft-delete filter. Filter needs to be removed from entity manager's event listeners:
// initiate an array for the removed listeners
$originalEventListeners = [];
// cycle through all registered event listeners
foreach ($em->getEventManager()->getListeners() as $eventName => $listeners) {
foreach ($listeners as $listener) {
if ($listener instanceof \Gedmo\SoftDeleteable\SoftDeleteableListener) {
// store the event listener, that gets removed
$originalEventListeners[$eventName] = $listener;
// remove the SoftDeletableSubscriber event listener
$em->getEventManager()->removeEventListener($eventName, $listener);
}
}
}
// remove the entity
$em->remove($object);
$em->flush($object); // or $em->flush();
// re-add the removed listener back to the event-manager
foreach ($originalEventListeners as $eventName => $listener) {
$em->getEventManager()->addEventListener($eventName, $listener);
}
参考文献:
- https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/softdeleteable.md
- Force delete doctrine entity when using SoftDeletable by KnpLabs
- Disable Soft Deleteable filter for hard delete record doesn't work
这篇关于如何在symfony中禁用软删除(软删除)过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!