如何在 Laravel 中使用 chunk() 进行进度和失败更新?
Laravel Eloquent 模型称为 ProductModel,它引用包含大量行(即 500,000)的表。每行包含一个product_id,它调用函数isValid()
,该函数要么继续循环,要么中断循环。
https://laravel.com/docs/9.x/eloquent#chunking- results
我创建的用于说明问题的示例:(更新 16/03/22)
$log = array();
$log[] = ['Checking products...'];
$count = 0;
$chunks = 5000;
$total = ProductModel::count();
ProductModel::chunk($chunks, function ($products) uses (&$count, $log, $total) {
foreach ($products as $row) {
$this->isValid($row->product_id);
$count++;
}
$log[] = '[Success] Completed '. $count .' of '. $total .' records';
});
然后,循环的每个记录都存储在数组中$log
。
[Success] Completed 5,000 of 20,000 records
[Success] Completed 10,000 of 20,000 records
[Success] Completed 15,000 of 20,000 records
[Success] Completed 20,000 of 20,000 records
如果从 $this->isValid()
引发 Exception
,则数组 $log
应包含类似于以下内容的内容:
Checking products...
[Success] Completed 5,000 of 20,000 records
[Failed] Completed 7,402 of 20,000 records
Laravel Eloquent Model called ProductModel that references a table that contains a large number of rows (i.e. 500,000). Each row contains a product_id that calls the function isValid()
which either continues the loop or breaks it.
https://laravel.com/docs/9.x/eloquent#chunking-results
The example I have created to illustrate the problem: (UPDATED 16/03/22)
$log = array();
$log[] = ['Checking products...'];
$count = 0;
$chunks = 5000;
$total = ProductModel::count();
ProductModel::chunk($chunks, function ($products) uses (&$count, $log, $total) {
foreach ($products as $row) {
$this->isValid($row->product_id);
$count++;
}
$log[] = '[Success] Completed '. $count .' of '. $total .' records';
});
Each record of the loop is then stored in the array $log
.
[Success] Completed 5,000 of 20,000 records
[Success] Completed 10,000 of 20,000 records
[Success] Completed 15,000 of 20,000 records
[Success] Completed 20,000 of 20,000 records
If an Exception
is thrown from $this->isValid()
the array $log
should contain something similar to the following:
Checking products...
[Success] Completed 5,000 of 20,000 records
[Failed] Completed 7,402 of 20,000 records
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论