简体   繁体   English

如何使用Laravel 5对来自自定义查询的结果进行分块

[英]How to chunk results from a custom query with Laravel 5

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? 如果没有合适的口才ORM模型,是否可以进行分块? 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. 我尝试分块,因为如果查询返回太多结果,我将得到一个空白页(在任何日志中都找不到任何错误)。

I think right now it max 50.000 results that I can query at once. 我认为现在最多可以查询50.000个结果。 Is that maybe due to some restriction or limitation in Laravel? 那可能是由于Laravel的某些限制或限制吗?

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()的作用:

$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 向您的SQL查询LIMIT 200添加一个限制
  2. Increase the offset with every query you run. 您运行的每个查询都增加偏移量。 First 0, second 1 * 200, third 2 * 200 第一个0,第二个1 * 200,第三个2 * 200
  3. Do that until the result is returned empty (eg with a while loop like above) 这样做直到结果返回空(例如,上面的while循环)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM