Php JsonResource和;资源收集?在Laravel v6或v7中
有人能解释一下ResourceCollection和JsonResource之间的区别吗 在Laravel 6文档中,您可以生成两种不同类型的资源。。。ResourceCollection和JsonResourcePhp JsonResource和;资源收集?在Laravel v6或v7中,php,laravel,eloquent,laravel-6,laravel-7,Php,Laravel,Eloquent,Laravel 6,Laravel 7,有人能解释一下ResourceCollection和JsonResource之间的区别吗 在Laravel 6文档中,您可以生成两种不同类型的资源。。。ResourceCollection和JsonResource ResourceCollection用于项目列表,但JsonResource用于单个项目 我复制了一段在我的项目中使用它的代码: 在我的项目中,我有一个文章列表,所以我必须显示文章列表,所以我使用了ResourceCollection返回一个文章数组: <?php namesp
ResourceCollection
用于项目列表,但JsonResource
用于单个项目
我复制了一段在我的项目中使用它的代码:
在我的项目中,我有一个文章列表,所以我必须显示文章列表,所以我使用了ResourceCollection
返回一个文章数组:
<?php
namespace App\Http\Resources\Api\Collection;
use Illuminate\Http\Resources\Json\ResourceCollection;
class AlbumCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return $this->collection->map(function ($item) {
return [
'id' => $item->id,
'name' => $item->name,
'description' => $item->description
];
});
}
public function with($request)
{
return [
'status' => true
];
}
}
集合用于多个资源
我习惯这样做,例如:
客户实体集合:
public function toArray($request)
{
return [
'data' => $this->collection->map(function ($row) use ($request) {
return (new ClientEntityResource($row))->toArray($request);
})
];
}
客户资源
public function toArray($request)
{
$data = [
'type' => 'cliententity',
'id' => $this->clienteEntidadeId,
'clienteEntidadeNome' => $this->clienteEntidadeNome,
];
return $data;
}
然后,在我的控制器中,我可以调用完整的列表:
return (new ClientEntityCollection($rows))
->response()
->setStatusCode(200);
或单个项目:
return (new ClientEntityResource($row))
->response()
->setStatusCode(200);
它就像一个符咒,具有分页和所有..一个集合包含多个项目。资源是单个项目。这就像一袋苹果对一个苹果。
public function toArray($request)
{
$data = [
'type' => 'cliententity',
'id' => $this->clienteEntidadeId,
'clienteEntidadeNome' => $this->clienteEntidadeNome,
];
return $data;
}
return (new ClientEntityCollection($rows))
->response()
->setStatusCode(200);
return (new ClientEntityResource($row))
->response()
->setStatusCode(200);