【问题标题】:How to add meta data in laravel api resource如何在 laravel api 资源中添加元数据
【发布时间】:2022-01-16 06:23:11
【问题描述】:

我在前端站点使用 laravel api 资源。

实际上我也使用 laravel 分页来处理 FRONT-END 中的分页。

api资源结构如下:

{
    "data": [...],
    "links": [...], // handle pagination
    "meta": [...] // handle pagination
}

但我想在不考虑分页的情况下发送查询结果计数。例如,我将数据库结果分页到30 pre_page 并且所有查询结果是 200 我想将此计数发送到前端查看

我决定获取查询结果的计数,并给资源收集和重组 laravel api 资源。

{
    "data": [...],
    "metadata": {
        "count": 200
    },
    "links": [...], // handle pagination
    "meta": [...] // handle pagination
}

您还知道,也许我想向此集合添加其他数据。例如conversion ratemetadata,我不知道该怎么做。

【问题讨论】:

    标签: php laravel api


    【解决方案1】:

    我找到了我可以做到这一点的方法

    其实我只需要使用 additional 方法来获取 laravel 资源,例如:

    $data = Project::limit(100)->get();
    return ProjectResource::collection($data)->additional(['some_id => 1']);
    

    【讨论】:

      【解决方案2】:

      top-level-meta-data

      您需要创建一个ResourceCollection,然后在with 函数中定义额外的元变量。

      <?php
      
      namespace App\Http\Resources;
      
      use Illuminate\Http\Resources\Json\ResourceCollection;
      
      class UserCollection extends ResourceCollection
      {
          /**
          * Transform the resource collection into an array.
          *
          * @param  \Illuminate\Http\Request  $request
          * @return array
          */
          public function toArray($request)
          {
              return parent::toArray($request);
          }
      
          /**
          * Get additional data that should be returned with the resource array.
          *
          * @param  \Illuminate\Http\Request  $request
          * @return array
          */
          public function with($request)
          {
              return [
                  'meta' => [
                      'key' => 'value',
                  ],
              ];
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-26
        • 2021-01-05
        • 2018-04-08
        • 2020-05-17
        • 2021-01-30
        • 1970-01-01
        相关资源
        最近更新 更多