让我们看看以下例子:
User::where('is_active', true)->each(function (User $user){
// do something
}, 500);
因此,如果我有2000个用户,那么每次新用户结束时是否有办法做某事?
答案 0 :(得分:1)
User::where('is_active', true)->chunk(500, function (Collection $users) {
$users->each(function (User $user) {
// Do per-user stuff here
});
// Do per-chunk stuff here
}
这应该可以解决问题。请记住,最后一个块可能包含少于500个用户。如果它必须恰好是每500个,检查集合大小;
User::where('is_active', true)->chunk(500, function (Collection $users) {
$users->each(function (User $user) {
// Do per-user stuff here
});
if ($users->count() == 500) {
// Do per-chunk stuff here
}
}
希望这有帮助。
答案 1 :(得分:0)
如果您想使用each()
帮助程序,则需要手动执行此操作。做这样的事情:
$counter = 0;
$chunk = 500;
User::where('is_active', true)->each(function (User $user) use(&$counter, $chunk) {
// Do stuff for each user.
$counter += 1;
if ($counter === $chunk) {
$counter = 0;
// Do something after each chunk.
$this->doSomething();
}
}, $chunk);
if (!$counter)
// Do something for the last chunk.
$this->doSomething();
}