美好的一天.我想知道我是否可以在API响应中使用分块传输编码(进一步的CTE)?我在数据库中有大量数据,我需要在一个请求中将其传输到客户端.我已经阅读了很多关于CTE机制的内容,但不幸的是我找不到如何实现它.
值得一提的是:没有分页.它应该是一个自治系统,它将数据返回给客户端点,而不是网页.
正如我所提到的,数据存储在数据库中.唯一的问题是如何将数据拆分成段(块)并在一个API响应中逐个发送(一个一个).
谢谢.
解决方法:
我想您可能对查询生成器上的块方法感兴趣.
Chunking Results
If you need to work with thousands of database records, consider using
the chunk method. This method retrieves a small chunk of the results
at a time and feeds each chunk into a Closure for processing. This
method is very useful for writing Artisan commands that process
thousands of records. For example, let’s work with the entire users
table in chunks of 100 records at a time:
$response = new \Symfony\Component\HttpFoundation\StreamedResponse(function() {
$handle = fopen('php://output', 'w');
DB::table('users')->orderBy('id')->chunk(100, function ($users) use($handle) {
foreach ($users as $user) {
fputs($handle, json_encode($user));
}
});
fclose($handle);
});
return $response;
分块传输编码
据我所知,如果你返回一个JSON响应,我会知道Laravel does this by default.
更新:
我的解决方案不必要地复杂和复杂.我删除了StreamedResponse,因为确实没有任何需要它.请参阅下面的更新示例
$json_response = collect();
DB::table('users')->orderBy('id')->chunk(100, function ($users) use($json_response) {
foreach ($users as $user) {
$json_response->push($user);
}
});
return $json_response->toJson();
标签:php,http,rest,laravel,http-1-1
来源: https://codeday.me/bug/20190710/1424348.html