繁体   English   中英

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

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

跟进此问题: 如何在Laravel中对来自自定义查询的结果进行分块

我尝试

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

    //a bunch of code...

    }
});

但是我收到以下错误:

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

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

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

好吧,由于查询将仅返回对象数组,因此您可以简单地使用PHP的array_chunk()

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

这是雄辩模型上的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();
}

您可以尝试做类似的事情(尽管我认为应该可以一次全部运行您的查询,但是我不能帮您解决这个问题……)

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

暂无
暂无

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

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