如何在 Laravel 中使用 chunk() 进行进度和失败更新?

发布于 2025-01-11 04:27:15 字数 1265 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文