筛选收集

时间:2018-09-27 18:17:22

标签: symfony api-platform.com

有没有办法过滤集合,例如

class Company{

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\User", mappedBy="company", cascade={"persist","remove"})
     */
    public $users;

}

检查公司是否有用户的方式。但是我需要在公司方面进行过滤,因此发送请求/api/companies?somefilter

那么有没有办法检查集合是否为空?

1 个答案:

答案 0 :(得分:0)

您可以在创建用户关系时在设置为true的公司中添加布尔列。

因此,您可以为您的公司实体添加一个BooleanFilter,用于拥有用户的支票公司。

/**
 * @ApiResource
 * @ApiFilter(BooleanFilter::class, properties={"hasUsers"})
 */

或者您可以创建一个CustomFilter,在其中输入true或false并通过queryBuilder获取具有用户的公司

https://api-platform.com/docs/core/filters/#creating-custom-doctrine-orm-filters

    <?php
    // api/src/Filter/RegexpFilter.php

    namespace App\Filter;

    use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\AbstractContextAwareFilter;
    use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
    use Doctrine\ORM\QueryBuilder;

    final class RegexpFilter extends AbstractContextAwareFilter
    {
        protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
        {
            // otherwise filter is applied to order and page as well
            if (
                !$this->isPropertyEnabled($property, $resourceClass) ||
                !$this->isPropertyMapped($property, $resourceClass)
            ) {
                return;
            }

            $parameterName = $queryNameGenerator->generateParameterName($property); 
// Generate a unique parameter name to avoid collisions with other filters
            $queryBuilder
                ->andWhere(sprintf('REGEXP(o.%s, :%s) = 1', $property, $parameterName))
                ->setParameter($parameterName, $value);
        }

        // This function is only used to hook in documentation generators (supported by Swagger and Hydra)
        public function getDescription(string $resourceClass): array
        {
            if (!$this->properties) {
                return [];
            }

            $description = [];
            foreach ($this->properties as $property => $strategy) {
                $description["regexp_$property"] = [
                    'property' => $property,
                    'type' => 'string',
                    'required' => false,
                    'swagger' => [
                        'description' => 'Filter using a regex. This will appear in the Swagger documentation!',
                        'name' => 'Custom name to use in the Swagger documentation',
                        'type' => 'Will appear below the name in the Swagger documentation',
                    ],
                ];
            }

            return $description;
        }
    }