如何在 Symfony4 api-platform 中隐藏实体属性

use*_*311 6 php api symfony api-platform.com

我有这个实体

/**
* @ApiResource(
*       collectionOperations={
*           "get"={
*               "access_control"="is_granted('IS_AUTHENTICATED_FULLY')"
*           },
*           "post"={
*               "access_control"="is_granted('IS_AUTHENTICATED_FULLY')"
*           }
*       },
*       itemOperations={
*       "get"={
*               "access_control"="is_granted('ROLE_ADMIN') or object.getUser() == user"
*           },
*           "put"={
*               "access_control"="is_granted('ROLE_ADMIN') or object.getUser() == user"
*          },
*           "delete"={
*               "access_control"="is_granted('ROLE_ADMIN') or object.getUser() == user"
*          }
*       }
* )
* @ORM\Entity(repositoryClass="App\Repository\FeedRepository")
*/
class Feed implements AuthoredEntityInterface
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="feeds")
 * @ORM\JoinColumn(nullable=false)
 */
private $user;

/**
 * @ORM\Column(type="string", length=255)
 */
private $name;

/**
 * @ORM\Column(type="string", length=2083, unique=true)
 */
private $url;

//various getters and setters

}
Run Code Online (Sandbox Code Playgroud)

相关的 User 实体实现 UserInterface。该实体实现了一个接口,我用它来自动填充已登录用户的用户字段。

自动生成的 /api/feeds POST 端点需要 3 个参数:用户、名称和 url。

我想从端点中排除参数 user(因为是内部自动生成的)。我知道我可以不使用它,但这会在我收到此消息的测试中引起问题:

提供的值无效(IRI 无效?)

谢谢

Ken*_*ren 7

Symfony Serializer 支持@Groups注释,这使您支持根据给定组隐藏或显示字段。

API平台文档中有示例https://api-platform.com/docs/core/serialization/#using-serialization-groups

/**
 * @ApiResource(
 *     normalizationContext={"groups"={"read"}},
 *     denormalizationContext={"groups"={"write"}}
 * )
 */
class Book
{
    /**
     * @Groups({"read", "write"})
     */
    public $name;

    /**
     * @Groups("write")
     */
    public $author;

    // ...
}
Run Code Online (Sandbox Code Playgroud)