首页 > 解决方案 > 如何为子资源启用分页?

问题描述

在我的 API 配置文件中,我禁用了分页:

api_platform.yaml

api_platform:
    collection:
        pagination:
            enabled: false

但我想为特定的子资源启用分页:

父类:

/**
 * @ORM\Entity(repositoryClass="App\Repository\ForumRepository")
 * @ApiResource(
 *     collectionOperations={
 *         "get",
 *     },
 *     itemOperations={"get"},
 * )
 */
class Forum
{
    ...
    /**
     * @var ForumSubject[]|ArrayCollection
     *
     * @ORM\OneToMany(
     *     targetEntity="App\Entity\ForumSubject",
     *     mappedBy="forum",
     * )
     * @ApiSubresource(maxDepth=1)
     */
    private $subjects;
    ...

儿童班:

/**
 * @ORM\Entity(repositoryClass="App\Repository\ForumSubjectRepository")
 * @ApiResource(
 *     collectionOperations={
 *         "post",
 *     },
 *     itemOperations={
 *         "get",
 *         "put",
 *         "delete"
 *     },
 * )
 */
class ForumSubject
{
    ...

一切正常我可以访问我的子资源:( /api/forums/a21cb5db-aed7-45a6-884f-3d3e6d7abd8c/subjects 返回论坛的所有主题,路线名称:)api_forums_subjects_get_subresource

但我无法在这条路线上启用分页,文档没有提及任何内容。

经过研究,我尝试了这个,但没有任何效果

不适用于父类或子类:

 * @ApiResource(
 *     ...
 *     subresourceOperations={
 *         "api_forums_subjects_get_subresource"={"pagination_enabled"=true}
 *     }

不适用于父类;错误 un children 类(在 Swagger 规范中找不到操作“api_forums_subjects_get_subresource”)。

 * @ApiResource(
 *     ...
 *     collectionOperations={
 *         "get",
 *         "api_forums_subjects_get_subresource"={"pagination_enabled"=true}
 *     },

标签: symfonyapi-platform.com

解决方案


在查看 API 平台源代码后,解决方案如下:

儿童班:

 * @ApiResource(
 *     ...
 *     collectionOperations={
 *         ...
 *         "api_forums_subjects_get_subresource"={
 *             "method"="get", // don't forget : otherwise trigger a strange swagger error
 *             "pagination_enabled"=true
 *         }

推荐阅读