symfony - 将所有结果限制为特定的属性值(即 active=true)
问题描述
我正在使用带有 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;
...
}
解决方案
解决方案是使用 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 }
推荐阅读
- go - 检查我是否可以从频道读取
- php - 如何在没有集合的情况下使用 Eloquent Builder 进行 INTERSECT
- javascript - React 警告:无法对未安装的组件执行 React 状态更新。要修复,请取消所有订阅
- javascript - 如何在javascript中操作字符串升序和降序并存储在变量中
- node.js - 检索 POST 查询参数
- concurrency - 子文档变异操作无法与 XDCR 一起正常工作
- c# - 如何将对象移动到表单应用程序中的一组随机坐标
- python - Tensorflow 错误连接字符和词嵌入
- c++ - 列表插入迭代器超出范围错误
- node.js - 从heroku发出http请求