现在我有很多实体:
#[ORM\Column(type: 'datetime')]
#[Groups(['article_category:output'])]
/**
* @Timestampable(on="create")
*/
private \DateTime $createdAt;
public function getCreatedAt(): \DateTime
{
return $this->createdAt;
}
我想把它放在 Trait 里面。 但每个实体都有自己的标准化组(如“article_category:output”)。 如何使该字段始终可从 API 平台获取?
我们做了什么:
根据你的特质使用一组,例如
timestampable
trait TimestampableEntity
{
/**
* ...
* @Groups({"timestampable"})
*/
protected $createdAt;
...
}
然后,每当您想要公开时间戳时,将它们添加到您的配置中(您可以向一个操作添加多个组)
<?php
/**
* @ApiResource(
* collectionOperations= {
* "get" = {
* "normalization_context"={"groups"={"appointment:read", "timestampable"}},
* },
* },
* )
*/
class Appointment
{
use TimestampableEntity;
创建带有注释的新 getter,请参阅: https://github.com/api-platform/api-platform/issues/1358#issuecomment-611777550