如何在 api-platform GET 操作中始终过滤特定字段值的集合? [英] How to always filter a collection on specific field value in api-platform GET operations?
问题描述
在 GET 操作中,我想从返回的集合中排除我的实体具有等于true"的存档"字段.
In the GET operations, I'd like to exclude from the returning collections my entities that have an " archive" field that equals " true ".
我希望将其作为/users 或/companies 等端点的默认设置,并且我想避免手动添加 URL 过滤器,例如 /users?filter[archive]=true
I'd like that to be the default for my endpoints like /users or /companies and i want to avoid to add an URL filter by hand like /users?filter[archive]=true
最好的方法是什么?
感谢您的帮助:)
推荐答案
我不得不做类似的事情,我通过将 DoctrineExtension 应用到集合来解决它,该集合会将 WHERE 子句添加到 QueryBuilder.
I had to do something like that, and I solved it by applying a DoctrineExtension to a Collection that will add the WHERE clause to the QueryBuilder.
怎么样?
- 定义您的过滤器,我知道您已经拥有了.
- 将 Doctrine 扩展添加到仅应用于集合,或者如果需要,也添加到项目:https://api-platform.com/docs/core/extensions/#custom-doctrine-orm-extension
services:
App\Doctrine\Extension\ArchivedExtension:
tags:
- { name: api_platform.doctrine.orm.query_extension.collection }
- 对您的扩展程序进行编码.
您可以检查您是否收到某个过滤器"(您的filter[archive]=true"查询参数):如果是,请不要将条件应用于 QueryBuilder,您的过滤器将通过api平台.
You could check if you are receiving a certain "filter" (your "filter[archive]=true" query parameter): if YES, dont apply the condition to the QueryBuilder, your Filter will be applied by the filtering mechanism of ApiPlatform.
您的扩展类应该如下所示:
Your extension class should looked something like this:
class ArchivedExtension implements QueryCollectionExtensionInterface
{
public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null, array $context = [])
{
$this->addWhere($queryBuilder, $resourceClass, $context);
}
private function addWhere(QueryBuilder $queryBuilder, string $resourceClass, array $context = [])
{
if (MyResource::class !== $resourceClass) {
return;
}
// Search if a "archive" Filter is being requested, if not, apply a restriction to the QueryBuilder
if (array_key_exists('archive', $context['filters'])) {
return;
}
$rootAlias = $queryBuilder->getRootAliases()[0];
$queryBuilder->andWhere(sprintf('%s.archive = :archive', $rootAlias));
$queryBuilder->setParameter('archive', true);
}
}
这篇关于如何在 api-platform GET 操作中始终过滤特定字段值的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!