【发布时间】:2021-01-08 17:30:11
【问题描述】:
我有 2 条路线在控制器中命中 show() 和 index() 方法。模型名称为 Feed,有 4 个关系 FeedType、FeedImage、FeedVideo 和 FeedCaption。
当 API 命中 show() 方法时,我将通过 Feed 资源返回除 'thumbnail' 字段之外的所有字段和特定关系字段
class Feed extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'content' => $this->content,
'keywords' => $this->keywords,
'slug' => $this->slug,
'type' => new FeedTypeResource($this->feedType),
'images' => FeedImageResource::collection($this->feedImages),
'video' => new FeedVideoLinkResource($this->feedVideoLink),
'caption' => new FeedCaptionResource($this->feedCaption),
];
}
}
现在我只想返回 3 个字段 'title'、'thumbnail'、'created_at',其中一个关系字段 'name' 来自 FeedType当 API 命中 show() 方法时,通过资源的 strong> 关系。所以我创建了一个 FeedCollection 资源。但它给出了错误。
class FeedCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'title' => $this->title,
'thumbnail' => $this->thumbnail,
];
}
}
【问题讨论】:
-
什么错误,这是需要了解的重要信息......而且您可能正在处理单个实体而不是集合
标签: laravel