将所有结果限制为特定的属性值(即active = true)

时间:2018-07-15 22:21:21

标签: symfony api-platform.com

我正在使用带有API平台的Symfony 4。

我有一个Project实体,该实体具有布尔active属性。

我公开的API应该仅显示活动项目。

如何将在/api/projects处检索到的所有结果限制为active值为true的记录?

<?php
/**
 * @ApiResource(
 *     attributes={
 *     "normalization_context"={"groups"={"read"}},
 *     "denormalization_context"={"groups"={"write"}}
 *   },
 *   collectionOperations={"get"},
 *   itemOperations={"get"}
 * )
 * @ORM\Entity(repositoryClass="App\Repository\ProjectRepository")
 * @ORM\Table(name="project")
 */
class Project
{

    /**
     * @var int
     *
     * @Groups({"read"})
     * @ORM\Id
     * @ORM\Column(type="integer", options={"unsigned":true})
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var bool
     *
     * @ORM\Column(type="boolean", nullable=false)
     */
    private $active = false;

    ...
}

1 个答案:

答案 0 :(得分:1)

解决方案是使用Doctrine扩展名:https://api-platform.com/docs/core/extensions/#extensions

添加类和服务后,where子句将被注入Project集合和项目查询中。

src/Doctrine/ProjectAcctiveExtension.php

<?php

namespace App\Doctrine;

use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use Doctrine\ORM\QueryBuilder;

class ProjectActiveExtension implements QueryCollectionExtensionInterface
{
    /**
     * {@inheritdoc}
     */
    public function applyToCollection(
        QueryBuilder $qb,
        QueryNameGeneratorInterface $queryNameGenerator,
        string $resourceClass, string $operationName = null): void
    {
        $this->addWhere($qb, $resourceClass);
    }

    /**
     * {@inheritdoc}
     */
    public function applyToItem(
        QueryBuilder $qb,
        QueryNameGeneratorInterface $queryNameGenerator,
        string $resourceClass, array $identifiers,
        string $operationName = null,
        array $context = []): void
    {
        $this->addWhere($qb, $resourceClass);
    }

    /**
     * @param QueryBuilder $qb
     * @param string       $resourceClass
     */
    public function addWhere(QueryBuilder $qb, string $resourceClass): void
    {
        $rootAlias = $qb->getRootAliases()[0];
        $qb->andWhere(sprintf('%s.active = :active', $rootAlias));
        $qb->setParameter('active', true);
    }
}

services.yml

'App\Doctrine\ProjectActiveExtension':
    tags:
        - { name: api_platform.doctrine.orm.query_extension.collection, priority: 9 }
        - { name: api_platform.doctrine.orm.query_extension.item }