【发布时间】:2021-06-19 10:56:34
【问题描述】:
API 平台默认使用 IRI 来获取嵌套实体,但我正在尝试获取使用 normalization_context 和组进行规范化的实体。它起作用,但只有当我从嵌套实体中删除 @ApiResource 并且我需要它来公开我的 CRUD 服务时。
示例
/**
* @ApiResource(
* attributes={
* "normalization_context"={"groups"={"goals-read"}},
* "denormalization_context"={"groups"={"goals-read"}}
* })
*
* )
*
* Goals
* @ApiFilter(OrderFilter::class, properties={"id"}, arguments={"orderParameterName"="order"})
* @ORM\Table(name="goals", indexes={@ORM\Index(name="IDX_C7241E2FA55629DC", columns={"processus_id"})})
* @ORM\Entity
*/
class Goals
{
/**
* @var int
* @Groups("goals-read")
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
// some fields ...
/**
* @var Processus
* @ORM\ManyToOne(targetEntity="Processus")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="processus_id", referencedColumnName="id")
* })
* @Groups({"goals-read"})
* @ApiProperty(readableLink=false, writableLink=false)
*/
private $processus;
/**
* @var Issues
* @ORM\ManyToOne(targetEntity="Issues")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="issues_id", referencedColumnName="id")
* })
* @Groups({"goals-read"})
* @ApiProperty(readableLink=false, writableLink=false)
*/
private $issue;
进程类
/**
* Processus
* @ApiResource()
* @ORM\Table(name="processus", indexes={@ORM\Index(name="IDX_EEEA8C1DC35E566A", columns={"family_id"})})
* @ORM\Entity
*/
class Processus
{
/**
* @var int
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
* @Groups({"goals-read"})
*/
private $id;
/**
* @var string|null
* @ORM\Column(name="name", type="string", length=255, nullable=true)
* @Groups({"goals-read"})
*/
private $name;
响应正文
{
"@context": "/api/contexts/Goals",
"@id": "/api/goals",
"@type": "hydra:Collection",
"hydra:member": [
{
"@id": "/api/goals/29",
"@type": "Goals",
"id": 29,
"description": "string",
"comment": "string",
"currentState": "string",
"goalToReach": "string",
"advancement": "string",
"indicator": 0,
"q1": "string",
"q2": "string",
"q3": "string",
"q4": "string",
"nextYear": "string",
"nextTwoYear": "string",
"processus": "/api/processuses/2",
"issue": "/api/issues/5"
}
删除@ApiResource()时
// JSON 响应
...
...
...
"processus": {
"@type": "Processus",
"@id": "_:938",
"id": 2,
"name": "string"
}
【问题讨论】:
-
考虑从
denormalization_context组中删除goals-read,因为非规范化组用于指定传入有效负载,而不是传出有效负载。您是否尝试在不使用attribute属性的情况下使用配置上下文?例如@ApiResource(normalizationContext={"groups"={"goals-read"}})。或者通过在collectionOperationsGET操作下配置normalization_context来代替?
标签: json symfony normalization api-platform.com symfony5