php - Laravel 5 批量插入关系

标签 php mysql performance laravel laravel-5

我需要批量插入大量数据到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 完成对项目的循环。

最佳答案

首先,加载所有用户。但是只选择 idemail:

$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/

相关文章:

JavaBridge 不打开 php(无法连接到服务器)

php - Magento 仅显示至少购买过一次的产品

php - 在 PHP 查询的下拉列表中输入 "Any"值

java - 使用 MySQL 检查用户名和密码

javascript - jQuery append 一个元素数组

multithreading - 多线程能提高性能吗?如何?

php - 当我在 laravel 的 View 页面上调用 foreach 循环时,它不显示数据

php - MySQL:仅获取结果集的计数

php - 将 MySQL 数据加载到 PHP

c# - 整数与 double 算术性能?