2017-11-07 4 views
0

Eloquentを使用して、chunk関数の閉包内の条件に基づいてチャンクを終了するにはどうすればよいですか?私は戻ってみましたが、それは現在のチャンクだけを終了するように見えますが、すべてのチャンクは終了していないようです。この時点で、データベースからのレコードの取得を停止したいと考えています。閉鎖からの奇妙なチャンクの終了方法

$query->chunk(self::CHUNK_SIZE, function ($objects) { 
    if (someCondition) { 
     // terminate chunking here 
     return; 
    } 
}); 

答えて

1

もしあなたがreturn falseなら、それは壊れます。 do whileループにあり、returnであれば、ループを終了します。下のソースコードでは、次のように表示されます。

 if ($callback($results) === false) { 
      return false; 
     } 

これは、終了する機会を与えます。応答のための

/** 
    * Chunk the results of the query. 
    * 
    * @param int $count 
    * @param callable $callback 
    * @return bool 
    */ 
    public function chunk($count, callable $callback) 
    { 
     $this->enforceOrderBy(); 
     $page = 1; 
     do { 
      // We'll execute the query for the given page and get the results. If there are 
      // no results we can just break and return from here. When there are results 
      // we will call the callback with the current chunk of these results here. 
      $results = $this->forPage($page, $count)->get(); 
      $countResults = $results->count(); 
      if ($countResults == 0) { 
       break; 
      } 
      // 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. 
      if ($callback($results) === false) { 
       return false; 
      } 
      $page++; 
     } while ($countResults == $count); 
     return true; 
    } 

https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Concerns/BuildsQueries.php#L18

+0

感謝。残念ながら、それは 'break'を好きではありません。 "1レベルを壊すことはできません。" – Brian

+0

それをさらに調べた後に私の答えを編集しただけで、偽を返す必要があるようです。 –

+0

ありがとう!それが私に必要なことでした。 – Brian

関連する問題