Laravel chunk returns null

泪湿孤枕 提交于 2019-12-24 17:07:18

问题


I'm needing to chunk my query as it's making PHP run out of memory, however the below code just dumps null:

$chunked = $query->chunk(25, function ($events) {
    //dd($events);
});
dd($chunked);

However, when I do the below, it dumps the first chunk of 25:

$chunked = $query->chunk(25, function ($events) {
    dd($events);
});
//dd($chunked);

No combination of changing dd($events); to the likes of return $events, return true, iterating over each item in each chunk and returning that - works.

Am I stupid/doing something wrong or is this not working like it should?


回答1:


chunk() is a helper method which you can use on an instance of Query Builder or Eloquent Builder. In both cases, the method returns void:

  • Query Builder
  • Eloquent Builder

This means that your $chunked variable will be always empty.

The syntax you need to employ is the following:

Query Builder

DB::table('users')->chunk(100, function($users) {
    foreach ($users as $user) {
        //
    }
});

Eloquent

Flight::chunk(200, function ($flights) {
    foreach ($flights as $flight) {
        //
    }
});

Basically, all you need to do is to use a loop within the callback function of chunk() to modify your results.



来源:https://stackoverflow.com/questions/31489440/laravel-chunk-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!