我想知道是否可以为项目资源和集合资源定义不同的数据。
对于收藏,我只想发送['id', 'title', 'slug']
,但项目资源将包含额外的详细信息['id', 'title', 'slug', 'user', etc.]
我想实现类似:
class PageResource extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'user' => [
'id' => $this->user->id,
'name' => $this->user->name,
'email' => $this->user->email,
],
];
}
}
class PageResourceCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
];
}
}
PageResourceCollection将无法按预期工作,因为它使用PageResource所以它需要
return [
'data' => $this->collection,
];
我可以将资源复制到PageFullResource
/PageListResource
和PageFullResourceCollection
/PageListResourceCollection
但我试图找到一种更好的方法来实现相同的结果。