如何解决如何使用laravel JsonResource为多态关系生成json响应
如何使用laravel JsonResource为多态关系生成json响应。考虑下面的例子
使用 Illuminate\Database\Eloquent\Relations\MorphTo;
$activities = ActivityFeed::query()
->with(['parentable' => function (MorphTo $morphTo) {
$morphTo->morphWith([
Event::class => ['calendar'],Photo::class => ['tags'],Post::class => ['author'],]);
}])->get();
return ActivityResource::collection($activities);
活动提要的父级可以是任何内容,例如:事件、照片、帖子等。因此,在“ActivityResource”类中,我比较下面的“parentable”类,然后相应地生成“属性”。
if (get_class($this->parentable) == 'App\Event')
if (get_class($this->parentable) == 'App\Photo')
if (get_class($this->parentable) == 'App\Post')
有没有更好的方法来做到这一点?我期待像下面这样的 json 响应。
[
{
"id": "60b0571e7ac3cf82df766b6a","type": "Post","attributes": {
"title": "test title","body": "test body","publishedAt": "28th May 2021 09:00"
}
},{
"id": "60b0571e6fe2e9f2e5f63077","type": "Photo","attributes": {
"url": "https://example.com/example.jpeg","size": "12345","fileType": "jpeg"
}
},{
"id": "60b0571e54afa9d8d44d9786","type": "Event","attributes": {
"name": "This is a test event","place": "Texas","startsAt": "28th May 2021 09:00","endsAt": "28th May 2021 11:00"
}
}
]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。