我需要批量插入大量数据到mysql。大约 50 万行,与 Laravel 5.3 中的关系(困难部分)
表是车辆、用户和user_vehicle
Plain vehicles 插入数组看起来像这样:
$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 秒让 php 完成对项目的循环。
最佳答案
首先,加载所有用户。但是只选择 id
和 email
:
$users = User::pluck('email', 'id')->toArray();
这将创建一个具有 [id => email]
结构的数组。
然后您就可以使用这个数组而无需执行额外的查询:
$userId = $users[$email];
然后在vehicle_user
数据透视表中添加bigint
类型的id
列。为此表创建单独的 block 数组并使用关系的批量插入而不是使用 attach()
方法。
关于php - Laravel 5 批量插入关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41203510/