在使用 Api-Platform 构建 API 的过程中,有时需要使用 Doctrine 过滤器来限制查询结果。但是,可能会发现在使用 itemOperations 时,这些过滤器似乎不起作用。
这是因为 Api-Platform 使用了表格化查询语言 (DQL) 来处理 itemOperations,而 Doctrine 过滤器仅应用于实体的开发时查询。因此,需要使用自定义操作和控制器来应用过滤器。
下面是一个示例代码,演示了如何使用自定义操作和控制器来应用过滤器:
use ApiPlatform\Core\Annotation\ApiResource; use Doctrine\ORM\Mapping as ORM; use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;
/**
itemOperations={
"get"={
"controller"=MyEntityGetController::class,
},
"my_custom_operation"={
"method"="GET",
"path"="/my_entities/{id}/my_custom_operation",
"controller"=MyEntityCustomController::class,
}
},
attributes={
"filters"={SearchFilter::class}
}
namespace App\Controller;
use App\Entity\MyEntity; use Doctrine\ORM\QueryBuilder; use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface; use ApiPlatform\Core\Exception\ResourceNotFoundException; use ApiPlatform\Core\Exception\RuntimeException; use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response;
class MyEntityGetController extends AbstractController { public function __invoke(MyEntity $data): MyEntity