我正在尝试以易于使用的方式转换给定的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!';
}
文件收集资源:
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 中的'meta'不存在,也不存在其中的字段文件资源。仍然显示所有字段,例如30+(而不是FileResource中要求的8)。
我在这里想念东西吗?
当使用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()? (我仍然有30多个字段,而不是8个字段。)
PS:我真的不明白为什么我需要调用toArray(),在他们的文档中没有写成https://laravel.com/docs/5.8/eloquent-resources。