php - Laravel - 如何递归地将 API 资源转换为数组?
问题描述
我正在使用 Laravel API 资源并希望将实例的所有部分转换为数组。
在我的PreorderResource.php
:
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'exception' => $this->exception,
'failed_at' => $this->failed_at,
'driver' => new DriverResource(
$this->whenLoaded('driver')
)
];
}
然后解决:
$resolved = (new PreorderResource(
$preorder->load('driver')
))->resolve();
乍一看,resolve方法适合它,但问题是它不能递归地工作。我的资源解析如下:
array:3 [
"id" => 8
"exception" => null
"failed_at" => null
"driver" => Modules\User\Transformers\DriverResource {#1359}
]
如何以递归方式将 API 资源解析为数组?
解决方案
通常,您应该这样做:
Route::get('/some-url', function() {
$preorder = Preorder::find(1);
return new PreorderResource($preorder->load('driver'))
});
因为这是应该使用响应的方式(当然你可以从你的控制器中做到这一点)。
但是,如果您出于任何原因想要手动执行此操作,您可以执行以下操作:
Route::get('/some-url', function() {
$preorder = Preorder::find(1);
$jsonResponse = (new PreorderResource($preorder->load('driver')))->toResponse(app('request'));
echo $jsonResponse->getData();
});
我不确定这是否是您想要的确切效果,但如果需要,您还可以从中获取其他信息$jsonResponse
。结果->getData()
是对象。
您还可以使用:
echo $jsonResponse->getContent();
如果您只需要获取字符串
推荐阅读
- ionic-framework - 有谁知道如何将 sip.js 版本 0.8 或更高版本与电子(桌面应用程序)或离子(移动应用程序)一起使用?
- html - 我该如何解决这个相对/绝对问题?
- if-statement - 将两个嵌套的 IF 语句与多个条件相结合
- php - 建议在 mysql 中构建我的数据 - 主键 - 覆盖行
- java - @Delete 返回 HTTP 状态 405 - 方法不允许
- java - 如何从 Linux 运行 selenium webdriver(目前在 Windows 中工作)?
- apache-kafka - 如何配置 Yahoo Kafka-manager?
- python - 用python中的元组制作成员向量
- javascript - 编写嵌套的 GraphQL 突变
- go - 在继承结构上使用链方法