gpt4 book ai didi

php - json 资源和资源集合有什么区别?在 Laravel

转载 作者:行者123 更新时间:2023-12-03 12:43:33 31 4
gpt4 key购买 nike

有人可以解释 ResourceCollection 和 JsonResource 之间的区别吗?

在 Laravel 6 文档中,您可以生成 2 种不同类型的资源……ResourceCollection 和 JsonResource。
https://laravel.com/docs/6.x/eloquent-resources#resource-responses

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class ShopCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}


对...
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Shop extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}

最佳答案

当您将单个模型转换为 json 时,即为 json 资源,当您将模型集合转换为 json 时,即为资源集合。

如果您要返回资源集合或作为集合的分页响应。

documentation

to generating resources that transform individual models, you may generate resources that are responsible for transforming collections of models. This allows your response to include links and other meta information that is relevant to an entire collection of a given resource.

关于php - json 资源和资源集合有什么区别?在 Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58315376/

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