laravel chunk result set processing block
Brief introduction
If you need to handle hundreds of database records, consider using chunk
method of obtaining a small piece of a result set, each tile is then passed several
data processing to the closure functionadvantage:
Using the
chunk
method can be effectively reduced memory consumption when handling large amounts of data collection
Code
//场景:player表有很多数据,分块处理每次操作100条,而不是一次性操作整个数据库
Player::chunk(100, function($players){
foreach($players as $player) {
$player->display_status = 1;
$player->save();
//DB::table('player')->where('id',$player->id)->update(['display_status'=>1]);
}
});
//闭包函数中返回 false 来终止组块的运行
DB::table('player')
->orderBy('id')
->chunk(100, function($players){
// 处理结果集...
return false;
});