[英]api-platform filter out the soft deleted items
I have setup the soft delete for my Store entity by using softdelete .我已经使用softdelete为我的 Store 实体设置了软删除。
This is my filter setup in the doctrine.yml
:这是我在doctrine.yml
中的过滤器设置:
doctrine:
# ...
orm:
# ...
filters:
softdeleteable:
class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
enabled: true
So when I hit eg the URL /stores
only the active stores are returned, but if I change the config to enabled: false
it will give me all the results including deleted items, which is correct.因此,当我点击例如 URL /stores
时,仅返回活动商店,但如果我将配置更改为enabled: false
它会给我所有结果,包括已删除的项目,这是正确的。
Now what I want to achieve is pass a query parameter from front-end like /stores?deleted=1
and then I want to get all the data, if no deleted=1
found only the active items现在我想要实现的是从前端传递一个查询参数,例如/stores?deleted=1
然后我想获取所有数据,如果没有deleted=1
只找到活动项目
Why not create an event listener that uses the Request
object and Doctrine's entity manager, and disables this filter?为什么不创建一个使用Request
object 和 Doctrine 的实体管理器的事件侦听器,并禁用此过滤器? Something like this:像这样的东西:
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');
}
}
}
Since answer from @nico-haase didn't work for me, I am posting similar solution that works for me using Symfony 5.3 and Api Plarform 2.6:由于@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');
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.