簡體   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