问题描述
我有一个包含许多外键的不同部分的 API,例如 category_id 用于帖子和类别,user_id 用于用户和帖子,parent_id > 用于类别和子类别以及 ...
"post": {
"id": 1,"category_id": 2,"user_id": 1,"title": "Is there a vaccine for COVID-19?","body": "Yes there are Now several vaccines that are in use. The first mass vaccination programme started in early December 2020 and the number of vaccination doses administered is updated on a daily basis here. At least 13 different vaccines (across 4 platforms) have been administered.\r\n\r\nThe Pfizer/BioNtech Comirnaty vaccine was listed for WHO Emergency Use Listing (EUL) on 31 December 2020. The SII/Covishield and AstraZeneca/AZD1222 vaccines (developed by AstraZeneca/Oxford and manufactured by the State Institute of India and SK Bio respectively) were given EUL on 16 February. The Janssen/Ad26.COV 2.S developed by Johnson & Johnson,was listed for EUL on 12 march 2021. The Moderna COVID-19 vaccine (mRNA 1273) was listed for EUL on 30 April 2021 and the Sinopharm COVID-19 vaccine was listed for EUL on 7 May 2021. The Sinopharm vaccine is produced by Beijing Bio-Institute of Biological Products Co Ltd,subsidiary of China National Biotec Group (CNBG). The Sinovac-CoronaVac was listed for EUL on 1 June 2021.","study_time": "2","likes": 5,"dislikes": 1,"created_at": "2021-06-26T16:40:59.000000Z",},"comments": [
{
"id": 1,"parent_id": null,"name": "person1","email": "person1@gmail.com","comment": "not good","likes": 0,"dislikes": 2,"replies": [
{
"id": 2,"parent_id": 1,"name": "person2","email": "person@gmail.com","comment": "ok","likes": 1,"dislikes": 0,"replies": [
{
"id": 3,"parent_id": 2,"name": "person3","email": "example@gmail.com","comment": "good","dislikes": 0
}
]
}
]
}
],"post_views": 10
}
正如你在这篇文章中看到的,我有 category_id
和 user_id
以及 parent_id
评论
如何在 json 响应中显示类别的标题或用户名称而不是他们的 ID?
解决方法
如果您想自定义 Eloquent 模型的序列化方式,可以使用 Eloquent resources
。
您可以创建一个 PostResource
来定义您希望如何序列化您的 Post
模型。举个例子:
class PostResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,'category' => $this->category->name,'user' => $this->author->name,'comments' => CommentResource::collection($this->comments),];
}
}
请注意,您可以调用其他 Resource
类来执行嵌套关系的自定义。
您也可以创建一个 CommentResource
和 RepliesResource
来为它们进行映射。
然后您将返回您的 PostResource
,例如:
return new PostResource(Resource::first());