4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel で chunk を途中で止めたいとき。

Last updated at Posted at 2017-08-18

今まで最後まで回してばかりで、気にもしていなかったのですが、昨日 chunk()で回している間に辛い出来事があって、途中で止めたくなったのでどうやって止めるのかをさらっと調べました。

結果

chunk() に渡しているコールバック関数内で return false; すれば途中で止めることができる。

sample.php
<?php
Flight::chunk(200, function ($flights) {
    foreach ($flights as $flight) {
        // 何か処理
    }
    return false; // 最初の200件で取得終了
});

おまけ

API ドキュメントにも特に記載はないけれど、ソース見たらこんな感じでした。
ソースへのリンク

chunk.php
<?php
/**
 * Chunk the results of the query.
 *
 * @param  int  $count
 * @param  callable  $callback
 * @return bool
 */
public function chunk($count, callable lback)
{
    $this->enforceOrderBy();
    $page = 1;
    do {
        // We'll execute the query for the given  and get the results. If there are
        // no results we can just break and rn from here. When there are results
        // we will call the callback with the ent chunk of these results here.
        $results = $this->forPage($page, nt)->get();
        $countResults = $results->count();
        if ($countResults == 0) {
            break;
        }
        // On each chunk result set, we will  them to the callback and then let the
        // developer take care of everything in the callback, which allows us to
        // keep the memory low for spinning ugh large result sets for working.
        if ($callback($results) === false) {
            return false;
        }
        $page++;
    } while ($countResults == $count);
    return true;
}

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?