检查代码以防止出现允许的内存限制问题
Review code to prevent allowed memory limit issue
虽然要做,但感觉自己的代码很烂。
我 运行 我的 Laravel 6.x 应用程序在 Docker 容器中。当 运行 下面的代码时,我得到
Allowed memory size of ** bytes exhausted (tried to allocate 8192 bytes)
无论我将 memory_limit
设置多高,它都是相同的错误(具有新限制)。所以我想查看我的代码:
// I'm running a seeder.
$arr = [1,2,3,4,5,.....];
// Get all users and update a column:
$users = Users:all();
// Loop and update (we have thousands )
foreach ($users as $user) {
$index = array_rand($arr);
$user->someColumn = $arr[$index];
$user->save();
}
// Another loop for another model with same as above.....
这导致了“允许的内存”问题。有没有更好的方法来实现这个?
与其一次获取所有用户,不如获取 chunk
个用户
\App\User::chunk(10, function ($users) use ($arr) {
foreach ($users as $user) {
$index = array_rand($arr);
$user->someColumn = $arr[$index];
$user->save();
}
});
虽然
我 运行 我的 Laravel 6.x 应用程序在 Docker 容器中。当 运行 下面的代码时,我得到
Allowed memory size of ** bytes exhausted (tried to allocate 8192 bytes)
无论我将 memory_limit
设置多高,它都是相同的错误(具有新限制)。所以我想查看我的代码:
// I'm running a seeder.
$arr = [1,2,3,4,5,.....];
// Get all users and update a column:
$users = Users:all();
// Loop and update (we have thousands )
foreach ($users as $user) {
$index = array_rand($arr);
$user->someColumn = $arr[$index];
$user->save();
}
// Another loop for another model with same as above.....
这导致了“允许的内存”问题。有没有更好的方法来实现这个?
与其一次获取所有用户,不如获取 chunk
个用户
\App\User::chunk(10, function ($users) use ($arr) {
foreach ($users as $user) {
$index = array_rand($arr);
$user->someColumn = $arr[$index];
$user->save();
}
});