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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28691898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:00:49  来源:igfitidea点击:

How to chunk results from a custom query with Laravel 5

phpmysqllaraveleloquentlaravel-5

提问by kritop

Following up on this Question: How to chunk results from a custom query in Laravel

跟进这个问题:如何从 Laravel 中的自定义查询中分块结果

I try

我试试

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

    //a bunch of code...

    }
});

But I get the following error:

但我收到以下错误:

FatalErrorException in MigrationController.php line 98:
 Call to a member function chunk() on array

Is chunking possible without having an appropriate Eloquent ORM Model? I try to chunk because I get a blank page (can't find any errrors in any log) if the query returns too many results.

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

I think right now it max 50.000 results that I can query at once. Is that maybe due to some restriction or limitation in Laravel?

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

回答by lukasgeiter

Well since the query will just return an array of objects you can simply use PHP's array_chunk():

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

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


Here's what chunk()on an eloquent model does:

以下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();
}

You could try to do something similar (although I think it should be possible to run your query all at once, but I can't help you with that...)

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

  1. Add a limit to your SQL query LIMIT 200
  2. Increase the offset with every query you run. First 0, second 1 * 200, third 2 * 200
  3. Do that until the result is returned empty (e.g. with a while loop like above)
  1. 为您的 SQL 查询添加限制 LIMIT 200
  2. 增加您运行的每个查询的偏移量。第一个0,第二个1*200,第三个2*200
  3. 这样做直到结果返回空(例如使用像上面的 while 循环)