【问题标题】:How can fetching huge records using Laravel and MySQL?如何使用 Laravel 和 MySQL 获取大量记录?
【发布时间】:2018-07-16 13:08:48
【问题描述】:

我需要专家的建议和解决方案。我们正在这里开发工作门户网站,处理大约 100 万条记录。我们正面临获取超时错误的记录。如何使用 laravel 和 MySql 处理这些记录?

我们正在尝试执行以下步骤:

  1. 增加 PHP 执行时间
  2. MySql 索引
  3. 分页

【问题讨论】:

    标签: mysql laravel laravel-5 laravel-eloquent laravel-query-builder


    【解决方案1】:

    来自the docs

    如果您需要处理数千条数据库记录,请考虑使用块方法。此方法一次检索一小块结果,并将每个块馈送到闭包中进行处理。这种方法对于编写处理数千条记录的 Artisan 命令非常有用。 例如,让我们一次处理 100 条记录的整个用户表:

    DB::table('users')->orderBy('id')->chunk(100, function ($users) {
        foreach ($users as $user) {
            //
        }
    });
    

    【讨论】:

    • 感谢您的回复。但是我们可以使用 laravel 通过 excel 进行导出报告。在这里我们可以怎么做?在块方法中,每次循环记录我们有 500k 记录,那么循环时间太多了。还有其他解决方案吗
    【解决方案2】:

    在处理大型数据集时,您应该对结果进行分块。这使您可以处理较小的负载,减少内存消耗,并允许您在提取/处理其余数据时将数据返回给用户。请参阅 laravel 文档分块:

    https://laravel.com/docs/5.5/eloquent#chunking-results

    为了进一步加快速度,您可以利用多线程并生成并发进程,每个进程一次处理一个块。 Symfony 的 Symfony\Component\Process\Process 类使这很容易做到。

    https://symfony.com/doc/current/components/process.html

    【讨论】:

      【解决方案3】:

      您好,我认为这可能会有所帮助

          $users = User::groupBy('id')->orderBy('id', 'asc');
      
          $response = new StreamedResponse(function() use($users){
              $handle = fopen('php://output', 'w');
              // Add Excel headers
              fputcsv($handle, [
                  'col1', 'Col 2'           ]);
              $users->chunk(1000, function($filtered_users) use($handle) {
                  foreach ($filtered_users as $user) {
                      // Add a new row with user data
                      fputcsv($handle, [
                          $user->col1, $user->col2
                      ]);
                  }
              });
              // Close the output stream
              fclose($handle);
              }, 200, [
                  'Content-Type' => 'text/csv',
                  'Content-Disposition' => 'attachment; filename="Users'.Carbon::now()->toDateTimeString().'.csv"',
              ]);
      
              return $response;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-02
        • 2018-03-03
        • 2022-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多