18
15

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 Eloquentで大量のデータを取得する場合

Posted at

LaravelのEloquentで大量のデータをgetすると、
メモリー違反が発生する場合があります。

そんなときは、getの代わりにchunkを使いましょう。


class SomeContent extends Eloquent {
}

のようなEloquent継承のクラスがあったとして、


SomeContent::where('created_at', '>=', Carbon\Carbon::yesterday()->toDateString())
    ->orderBy('id')
    ->chunk(100, function ($someContents) {
            foreach ($someContents as $someContent) {
                $someContent->touch();
            }
        }
    );

これで、100件ごとにデータが取得され、クロージャが実行されます。

18
15
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
18
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?