php - Laravel - 指定为集合资源返回的字段

标签 php laravel

我有这样一个集合资源:

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(或指定我返回的字段)?

最佳答案

您可以使用返回 AnonymousResourceCollectionAnonymousResourceCollection extends ResourceCollectionVechicleResource::collection(),所以您可以调用 preserveQuery()。然后您可以选择/指定要在 VechicleResource 中发送的字段。

public function toArray($request)
{
    return [
        'data' => VechicleResource::collection($this->collection),
    ];
}

关于php - Laravel - 指定为集合资源返回的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66369328/

相关文章:

php - oracle中的日期类型不包含时间值

php - 使用 php 在 mysql 数据库中跟踪单个客户的多个查询

Laravel Dusk 无法断言看到屏幕截图中可见的文本(使用 whenAvailable 作为模态)

testing - Laravel 4 - 单元测试

php - 有没有比使用 App\Entity\作为 E 更好的方法

PHP GAE 无法在本地运行 SDK

php - 检查是否在标题中

php - 自定义 session 变量的 session 生命周期

php - 从 Laravel 禁用密码重置

php - 寻找具有多个后端存储适配器的 PHP 缓存库