如何在symfony中禁用软删除

如何在symfony中禁用软删除

本文介绍了如何在symfony中禁用软删除(软删除)过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为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. 软删除的加载实体

  2. 删除实体从数据库完全绕过软删除过滤器

那么如何禁用它?

推荐答案

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();

尽管文档中没有提到,但如果您需要删除实体并绕过软删除过滤器,则第一个解决方案不起作用。过滤器需要从实体管理器的事件监听器中删除:

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

参考文献:

这篇关于如何在symfony中禁用软删除(软删除)过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!