我需要批量插入大量的數據到MySQL。大約50萬行,在Laravel關係(硬部分)5.3Laravel 5批量插入與關係
表是車輛,用戶和user_vehicle
普通車輛插入陣列看起來是這樣的:
$vehicles = array();
foreach ($data as $val) {
$temp = array(
'license_plate' => $val->license_plate,
'created_at' => $now,
'updated_at' => $now,
'state_id' => $activeState,
'type_id' => $typeId,
);
array_push($vehicles, $temp);
}
我可以成功地插入記錄等這:
$vehicles = array_chunk($vehicles, 10000);
foreach ($vehicles as $key => $vehicle) {
Vehicle::insert($vehicle);
}
它需要幾秒鐘來插入所有的數據和一切工作,但現在我需要添加關係到他們。由於一輛車可以屬於許多用戶(車主,司機等),因此我需要將某個用戶附加到某個車輛上。
現在,當我嘗試在這裏補充的關係也正是我堅持:
$vehicles = array();
$vehUsers = array();
$users = Users::get();
foreach ($data as $val) {
// Remap data to right structure
$temp = array(
'license_plate' => $val->license_plate,
'created_at' => $now,
'updated_at' => $now,
'state_id' => $activeState,
'type_id' => $typeId,
);
// Search for right user (This part is really slow)
$userId = $users->where('email', $val->email)->first();
if ($userId) {
$userId = $userId->id;
}
array_push($vehicles, $temp);
// Thought that it might help to save them into array for later use
array_push($vehUsers, $userId);
}
但問題是,我不能將其插入這樣
$vehicles = array_chunk($vehicles, 10000);
foreach ($vehicles as $key => $vehicle) {
Vehicle::insert($vehicle);
// Need to attach user here somehow
}
我需要運行他們在大塊(10K在我的情況)因爲1 1插入需要太長時間
// Insert them and relations one by one and it will take years
foreach ($vehicles as $key => $vehicle) {
$veh = Vehicle::insert($vehicle);
$veh->users()->attach($vehUsers[$key]);
}
我怎樣才能批量插入車輛他們的關係?
編輯:慢部分正在做數據庫查詢。我可以等10-20秒完成循環的項目。
感謝您的第一部分代碼。它真的讓事情更快=)並直接添加到vehicle_user與DB ::插入(bulk_data)的作品。只需要弄清楚如何從首次批量插入中獲取車輛ID。 –