gpt4 book ai didi

php - Laravel - 如何递归地将 API 资源转换为数组?

转载 作者:可可西里 更新时间:2023-11-01 00:39:10 25 4
gpt4 key购买 nike

我正在使用 Laravel API Resource并希望将我的实例的所有部分转换为数组。

在我的 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'))
});

因为这是应该使用响应的方式(当然您可以从您的 Controller 中执行此操作)。

但是,如果出于任何原因您想手动执行此操作,您可以执行以下操作:

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();

如果你只需要获取字符串

关于php - Laravel - 如何递归地将 API 资源转换为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52539291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com