0

特定の API 応答を操作しやすいものに変換しようとしています。

これは私がこれまでに持っているものです:

コントローラ:

public function drive()
{
    $optParams = [
        'corpora' => 'drive',
        'driveId' => env('GOOGLE_DRIVE_ID'),
        'includeItemsFromAllDrives' => true,
        'supportsAllDrives' => true,
        'fields' => 'files(*)'
    ];

    $results = $this->googleDrive->files->listFiles($optParams);
    $data = collect($results);
    $collection = new FileCollection($data);
    dd($collection);

    return 'Hi!';
}

FileCollection リソース:

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

ファイル リソース:

public function toArray($request)
{
    return [
        'name' => $this->resource['name'],
        'mime' => $this->resource['mimeType'],
        'parents' => $this->resource['parents'],
        'version' => $this->resource['version'],
        'webDownloadLink' => $this->resource['webContentLink'],
        'webLink' => $this->resource['webViewLink'],
        'modified_at' => $this->resource['modifiedTime'],
        'size' => $this->resource['size']
    ];
}

これは私が得ている結果です:

FileCollection {#223 ▼
  +collects: null
  +collection: Collection {#243 ▶}
  +resource: Collection {#243 ▼
    #items: array:2 [▼
      0 => File {#224 ▼
        +resource: Google_Service_Drive_DriveFile {#279 ▶}
        +with: []
        +additional: []
      }
      1 => File {#263 ▼
        +resource: Google_Service_Drive_DriveFile {#269 ▶}
        +with: []
        +additional: []
      }
    ]
  }
  +with: []
  +additional: []
}

ご覧のとおり、リソースのタイプは正しいのですが、何らかの理由でFileCollection「メタ」が存在せず、 Fileリソースのフィールドも存在しません。(FileResource で要求された 8 ではなく) 30+ のように、すべてのフィールドが引き続き表示されます。

ここで何か不足していますか?


編集:

toArray() メソッド ( $collection->toArray(null)) を使用してコレクションにアクセスすると、実際に適切な結果が得られます。

array:2 [▼
  "data" => Collection {#243 ▼
    #items: array:2 [▼
      0 => File {#224 ▶}
      1 => File {#263 ▶}
    ]
  }
  "meta" => array:1 [▼
    "files_count" => 2
  ]
]

では、このコレクションが FileResources の toArray() を使用していることを確認するにはどうすればよいでしょうか? (私はまだ 8 つではなく 30 を超えるフィールドを取得しています)。

PS: toArray() を呼び出す必要がある理由がよくわかりません。ドキュメントのどこにも書かれていません: https://laravel.com/docs/5.8/eloquent-resources

4

0 に答える 0