我已使用软删除为我的应用商店实体设置了软删除。
这是我在doctrine.yml
中的过滤器设置:
doctrine:
# ...
orm:
# ...
filters:
softdeleteable:
class: GedmoSoftDeleteableFilterSoftDeleteableFilter
enabled: true
因此,当我点击例如 URL/stores
时,只会返回活动存储,但是如果我将配置更改为enabled: false
它会给我所有结果,包括已删除的项目,这是正确的。
现在我想要实现的是像/stores?deleted=1
一样从前端传递一个查询参数,然后我想获取所有数据,如果没有deleted=1
只找到活动项目
为什么不创建一个使用Request
对象和 Doctrine 实体管理器的事件侦听器,并禁用此过滤器?像这样:
class FilterListener implements EventSubscriberInterface
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents(): array
{
return [
RequestEvent::class => 'onKernelRequest',
];
}
public function onKernelRequest(RequestEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
if ($request->query->getBoolean('deleted')) {
$this->entityManager->getFilters()->disable('softdeleteable');
}
}
}
由于 @nico-haase 的答案对我不起作用,我发布了类似的解决方案,该解决方案适用于使用 Symfony 5.3 和 API Plarform 2.6:
class FilterSubscriber implements EventSubscriberInterface
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['modifyFilters', EventPriorities::PRE_READ],
];
}
public function modifyFilters(RequestEvent $event)
{
$request = $event->getRequest();
// show deleted entities in case deleted param is provided
if ($request->query->getBoolean('deleted')) {
$this->entityManager->getFilters()->disable('softdeleteable');
}
}
}