我正在学习Laravel Resource API,并设置了控制器将数据传递给我的资源和资源集合。
这是服务器列表(index method),show method显示单个服务器
控制器
指数法
return new DedicatedServerResourceCollection($product->where('parent_id', 1)->with('dedicatedServers')->get());显示方法
return new DedicatedServerResource(DedicatedServer::findOrfail($id));我需要以不同的格式设置我的集合和资源。如何让我的资源集合循环遍历每一项并相应地格式化更改?
资源收集
return [
'productTypes' => $this->map(function($data){
return [
'id' => $data->id,
'title' => $data->title,
'tagline' => $data->tagline,
'slug' => $data->slug,
'dedicatedServers' => DedicatedServerResource::collection($this->resource)
// I need to pass 'dedicatedServers' === $this->dedicated_servers
];
})
];资源
return [
'id' => $this->id,
'productId' => $this->product_id,
'type' => $this->type,
'price' => $this->price,
'config' => [
'processorLine1' => $this->processor_line_1,
'processorLine2' => $this->processor_line_2,
'memory' => $this->memory,
'storageLine1' => $this->storage_line_1,
'storageLine2' => $this->storage_line_2,
'data' => $this->data,
'benchmark' => [
'benchmark' => $this->benchmark,
'benchmarkPercentage' => $this->benchmark_percentage
]
]
];发布于 2022-09-09 22:38:08
您应该使用“资源文件”或"$this->map(...)",而不是两者兼用。
指数法
return ProductCollection::make(Product::with('dedicatedServers')->get());ProductCollection
class ProductCollection extends ResourceCollection
{
public function toArray($request)
{
return [
'productTypes' => $this->collection,
];
}
}ProductResource
class ProductResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'tagline' => $this->tagline,
'slug' => $this->slug,
'dedicated_servers' => $this->whenLoaded('dedicatedServers'),
];
}
}DedicatedServerResource
class DedicatedServerResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'product_id' => $this->product_id,
'type' => $this->type,
'processor_line_1' => $this->processor_line_1,
'processor_line_2' => $this->processor_line_2,
'memory' => $this->memory,
'storage_line_1' => $this->storage_line_1,
'storage_line_2' => $this->storage_line_2,
'data' => $this->data,
'benchmark' => $this->benchmark,
'product' => ProductResource::make($this->whenLoaded('product')),
];
}
}注意:更愿意使用$this->whenLoaded('dedicatedServers')而不是$this->dedicatedServers来避免n+1问题。
发布于 2022-09-10 05:42:59
您可能希望为DedicatedServer模型创建一个不同的资源类,比如SecondDedicatedServerResource。
https://stackoverflow.com/questions/73657566
复制相似问题