在API Platform中,可以使用注解@ApiSubresource
来定义GraphQL模式中可为空的集合。下面是一个代码示例:
首先,需要在实体类中定义一个集合字段,并使用@ApiSubresource
注解来标识它是一个可为空的集合。例如,假设我们有一个User
实体类,它有一个posts
字段表示用户的帖子集合:
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Annotation\ApiSubresource;
/**
* @ApiResource
*/
class User
{
// ...
/**
* @var Post[]|null
*
* @ORM\OneToMany(targetEntity="App\Entity\Post", mappedBy="user")
* @ApiSubresource
*/
private $posts;
// ...
}
然后,需要在GraphQL模式中定义这个集合字段。可以在config/graphql/
目录下创建一个名为User.yaml
的文件,并添加以下内容:
App\Entity\User:
fields:
posts:
nullable: true
最后,重新加载GraphQL模式:
$ bin/console api:graphql:export
现在,你就可以在GraphQL查询中访问posts
字段,并且它可以返回一个空集合。
希望这个示例对你有帮助!