如何使用 Laravel 5 从自定义查询中分块结果

kri*_*top 3 php mysql laravel eloquent laravel-5

跟进这个问题:How to chunk results from a custom query in Laravel

我试试

DB::connection('mgnt')->select($query)->chunk(200, function($orders) {
    foreach ($orders as $order) { 

    //a bunch of code...

    }
});
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

FatalErrorException in MigrationController.php line 98:
 Call to a member function chunk() on array
Run Code Online (Sandbox Code Playgroud)

如果没有合适的 Eloquent ORM 模型,是否可以进行分块?我尝试分块,因为如果查询返回太多结果,我会得到一个空白页(在任何日志中都找不到任何错误)。

我认为现在最多可以查询 50.000 个结果。这可能是由于 Laravel 中的一些限制或限制吗?

luk*_*ter 5

好吧,由于查询只会返回一个对象数组,您可以简单地使用 PHP 的array_chunk()

$result = DB::connection('mgnt')->select($query);
foreach(array_chunk($result, 200) as $orders){
    foreach($orders as $order){
        // a bunch of code...
    }
}
Run Code Online (Sandbox Code Playgroud)

以下chunk()是 eloquent 模型的作用:

$results = $this->forPage($page = 1, $count)->get();

while (count($results) > 0)
{
    // On each chunk result set, we will pass them to the callback and then let the
    // developer take care of everything within the callback, which allows us to
    // keep the memory low for spinning through large result sets for working.
    call_user_func($callback, $results);

    $page++;

    $results = $this->forPage($page, $count)->get();
}
Run Code Online (Sandbox Code Playgroud)

你可以尝试做一些类似的事情(虽然我认为应该可以一次运行你的查询,但我无法帮助你......)

  1. 为您的 SQL 查询添加限制 LIMIT 200
  2. 增加您运行的每个查询的偏移量。第一个0,第二个1*200,第三个2*200
  3. 这样做直到结果返回空(例如,使用像上面那样的 while 循环)