微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

laravel 8 API 显示外键的标题或名称

如何解决laravel 8 API 显示外键的标题或名称

我有一个包含许多外键的不同部分的 API,例如 category_id 用于帖子和类别,user_id 用于用户和帖子,parent_id > 用于类别和子类别以及 ...

例如,我有一个帖子详细信息 json 响应:

 "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_iduser_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 类来执行嵌套关系的自定义。

您也可以创建一个 CommentResourceRepliesResource 来为它们进行映射。

然后您将返回您的 PostResource,例如:

return new PostResource(Resource::first());

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。