亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Symfony 5 API 填充相關對象實體

Symfony 5 API 填充相關對象實體

PHP
達令說 2023-07-15 15:35:15
我正在嘗試使用 Symfony 5 創建一個簡單的網絡應用程序。我正在使用API。目前,當調用某個端點時,它僅顯示相關鏈接的 IRI 鏈接:我需要顯示相關實體對象本身;如果我得到Item端點,相關實體Program應該返回:{? ? "id": 1,? ? "program": {? ? ? ? "id": 1,? ? ? ? "name": "First program"? ? },? ? "description": "fgdfg",? ? "comment": "dfgdfg"{因此,該表的外觀如下:我認為設置子資源就足以獲取對象,但事實并非如此:在InventoryItem實體配置屬性@ApiSubresource的注解中Program:/**?* @ORM\ManyToOne(targetEntity=Program::class, inversedBy="inventoryItems")?* @ORM\JoinColumn(nullable=false)?* @ApiSubresource?*/private $program;在resources.yaml文件中我配置了子資源:App\Entity\InventoryItem:? ?properties:? ? ? ?program:? ? ? ? ? ?subresource:? ? ? ? ? ? ? ?resourceClass: 'App\Entity\Program'? ? ? ? ? ? ? ?collection: true這仍然返回 IRI 而不是對象,唯一改變的是現在我可以訪問此 URL 中當前對象的相關實體:http://localhost:8000/api/inventory_items/1/program.json。關于如何返回相關實體對象本身而不是 IRI URL 有什么想法嗎?
查看完整描述

1 回答

?
蠱毒傳說

TA貢獻1895條經驗 獲得超3個贊

您正在搜索序列化您的商品。所以我想這更多的是序列化問題而不是子資源問題。我認為你應該使用序列化組而不是子資源。

SOLUTION1序列化嵌入關系

“嵌入關系”提供了書籍和作者的示例。

<?php

// api/src/Entity/Item.php


namespace App\Entity;


use ApiPlatform\Core\Annotation\ApiResource;

use Symfony\Component\Serializer\Annotation\Groups;


/**

?* @ApiResource(normalizationContext={"groups"={"item"}})

?*/

class Item

{

? ? /**

? ? ?* @Groups({"item"})

? ? ?*/

? ? public $description;


? ? /**

? ? ?* @Groups({"item"})

? ? ?*/

? ? public $comment;


? ? /**

? ? ?* @Groups({"item"})

? ? ?*/

? ? public $program;


? ? // ...

}


// api/src/Entity/Person.php


namespace App\Entity;


use ApiPlatform\Core\Annotation\ApiResource;

use Symfony\Component\Serializer\Annotation\Groups;


/**

?* @ApiResource

?*/

class Person

{

? ? /**

? ? ?* ...

? ? ?* @Groups("item") <=== This is item, not program but you can have two groups

? ? ?*/

? ? public $name;


? ? // ...

}

SOLUTION2混合子資源和序列化組

這個示例應該可以工作,但是(如果需要子資源)您也可以混合子資源和序列化,但在您的情況下,我認為第一個解決方案是最好的。


查看完整回答
反對 回復 2023-07-15
  • 1 回答
  • 0 關注
  • 129 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號