Фильтр по коллекции - PullRequest
       9

Фильтр по коллекции

0 голосов
/ 27 сентября 2018

Есть ли способ отфильтровать коллекцию, например,

class Company{

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

}

, чтобы проверить, есть ли у компании пользователи.Но мне нужно отфильтровать на стороне компании, поэтому отправьте запрос /api/companies?somefilter.

Итак, есть ли способ проверить, является ли коллекция пустой?

1 Ответ

0 голосов
/ 29 сентября 2018

Вы можете добавить логический столбец в компаниях, для которых вы установили значение true при создании отношения с пользователем.

Таким образом, вы можете добавить BooleanFilter к вашей компании для проверки компаний, у которых есть пользователи.

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

Или вы можете создать CustomFilter, в котором вы вводите true или false и получаете компании с пользователями с помощью queryBuilder

https://api -platform.com / docs / core / filters / # creation-custom-доктрин-ор-фильтры

    <?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;
        }
    }
...