如何始终在api平台GET操作中始终根据特定字段值过滤集合? [英] How to always filter a collection on specific field value in api-platform GET operations?

查看:61
本文介绍了如何始终在api平台GET操作中始终根据特定字段值过滤集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在GET操作中,我想从返回的集合中排除具有等于"true"的"archive"字段的实体.

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等端点的默认值,并且我希望避免像/users?filter [archive] = true 那样手动添加URL过滤器

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.

如何?

  1. 定义您的过滤器,我看到您已经拥有它.
  2. 仅将"Doctrine扩展名"添加到,或者仅在集合中添加项:

    services:
        App\Doctrine\Extension\ArchivedExtension:
            tags:
                - { name: api_platform.doctrine.orm.query_extension.collection }
    

    1. 为您的扩展程序编码.

    您可以检查是否接收到某个过滤器"(您的"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平台GET操作中始终根据特定字段值过滤集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆