如何在 laravel 8 中將 textarea 中的 1000000 行插入資料庫 ???????
我寫了這段代碼,只能插入 30000 行,然后瀏覽器給我 HTTP ERROR 500
我在 php.ini 中將 max_execution_time 設定為 300
這是我的代碼,請幫助我。謝謝
public function mobile_store(Request $request)
{
$data = $request->validate([
'mobile' => ['required', 'string', 'unique:mobiles,mobile'],
]);
$textAr = collect(explode("\r\n", $data['mobile']));
$ALL = $textAr->unique();
$Filter = $ALL->filter()->all();
$counter_unique = count($Filter);
$counter = count($textAr);
$insert_data = collect();
foreach ($Filter as $line) {
if (strlen($line) >= 10) {
$final = ' 98' . substr($line, -10);
}
$insert_data->push([
'mobile' => $final,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
}
foreach ($insert_data->chunk(5000) as $chunk) {
Mobile::insert($chunk->toArray());
}
return redirect()->back()->with('success', "There were $counter_unique rows in the list and $counter non-duplicate rows were entered");
}
uj5u.com熱心網友回復:
不要先存盤所有資料,只需使用 1 個 foreach,每 5000 條記錄存盤資料,然后重置陣列并執行下一批記錄。
$insert_data = collect();
$totalRecords = 0;
$batchCount = 0;
foreach ($Filter as $line) {
if (strlen($line) >= 10) {
$final = ' 98' . substr($line, -10);
}
$insert_data->push([
'mobile' => $final,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
if ( $batchCount == 5000 ) {
// Insert data
Mobile::insert($insert_data->toArray());
// Reset batch collection
$insert_data = collect();
// Reset counter of current batch
$batchCount = 0;
}
// Count of all records
$totalRecords ;
}
// Insert remaining records
if( $insert_data->count() > 0 )
Mobile::insert($insert_data->toArray());
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/432542.html
下一篇:5張表之間的關系發票
