【问题标题】:How to hide an entity property in Symfony4 api-platform如何在 Symfony4 api-platform 中隐藏实体属性
【发布时间】:2019-04-10 20:41:27
【问题描述】:

我有这个实体

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

}

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

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

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

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

谢谢

【问题讨论】:

    标签: php api symfony api-platform.com


    【解决方案1】:

    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;
    
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      • 2023-03-19
      • 2020-07-15
      相关资源
      最近更新 更多