我有这样一个集合资源:
class VehicleCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'data' => $this->collection,
];
}
}
我称之为,例如:
public function index()
{
$vehicles = Vehicle::where('id', '>', 0);
$collection = new VehicleCollection($vehicles->paginate(10));
return $collection->preserveQuery();
}
保留分页查询很重要,这就是为什么我没有使用 VechicleResource
- 它没有 preserveQuery()
的选项。
上面的代码工作正常,但返回的字段太多。例如,我的 Vehicle
表有一个 model_name
和一个 rating
列。我如何才能在此处为响应中的每个模型仅返回 model_name
(或指定我返回的字段)?
最佳答案
您可以使用返回 AnonymousResourceCollection
和 AnonymousResourceCollection
extends ResourceCollection
的 VechicleResource::collection()
,所以您可以调用 preserveQuery()
。然后您可以选择/指定要在 VechicleResource
中发送的字段。
public function toArray($request)
{
return [
'data' => VechicleResource::collection($this->collection),
];
}
关于php - Laravel - 指定为集合资源返回的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66369328/