要在API平台中添加带有子资源的新实体,您需要以下步骤:
使用Symfony命令行工具(CLI)创建新实体和子实体:
php bin/console make:entity Post
php bin/console make:entity Comment --regenerate
在新实体的注释中添加@ApiResource
注释,并使用subresourceOperations
参数指定子实体。下面是一个示例:
/**
* @ORM\Entity(repositoryClass=PostRepository::class)
* @ApiResource(
* subresourceOperations={
* "comments_get_subresource"={
* "method"="GET",
* "path"="/posts/{id}/comments"
* }
* }
* )
*/
class Post
{
// ...
}
在子实体的注释中添加@ApiResource
注释,并使用attributes
参数将其与父实体关联。下面是一个示例:
/**
* @ORM\Entity(repositoryClass=CommentRepository::class)
* @ApiResource(
* attributes={
* "normalization_context"={"groups"={"comment"}}
* }
* )
*/
class Comment
{
/**
* @ORM\ManyToOne(targetEntity=Post::class, inversedBy="comments")
* @ORM\JoinColumn(nullable=false)
*/
private $post;
// ...
}
在Post
实体中添加一个关联到子实体的属性和一个添加/删除子实体的方法。下面是一个示例:
/**
* @ORM\Entity(repositoryClass=PostRepository::class)
* @ApiResource(
* subresourceOperations={
* "comments_get_subresource"={
* "method"="GET",
* "path"="/posts/{id}/comments"
* }
* }
* )
*/
class Post
{
/**
* @ORM\OneToMany(targetEntity