简体   繁体   English

如何在Symfony4 API平台中隐藏实体属性

[英]How to hide an entity property in Symfony4 api-platform

I have this entity 我有这个实体

/**
* @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

}

The related User entity implements UserInterface. 相关的用户实体实现UserInterface。 This entity implements an interface I use to auto populate the user field with the logged user. 该实体实现了一个接口,该接口用于使用记录的用户自动填充用户字段。

The auto generated /api/feeds POST endpoint expects 3 parameters: user, name and url. 自动生成的/ api / feeds POST端点需要3个参数:用户,名称和url。

I want to exclude the parameter user from the endpoint (because auto-generated internally). 我想从端点中排除参数用户(因为在内部自动生成)。 I know I could just not to use it but this is causing problems in testing where I get this message: 我知道我不能使用它,但是这在测试我收到此消息的地方引起了问题:

Invalid value provided (invalid IRI?) 提供的值无效(无效的IRI?)

thanks 谢谢

Symfony Serializer supports @Groups annotation, which gives you support to hide or show fields based on given group. Symfony序列化程序支持@Groups批注,该批注支持您根据给定的组隐藏或显示字段。

There is example in API Platform docs https://api-platform.com/docs/core/serialization/#using-serialization-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;

    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM