首页 > 解决方案 > 如何制定最有效和最高效的逻辑来检查数据库中的数据是否存在?

问题描述

我使用 laravel 5.6

我有一个包含 50 万条记录的 json 文件。我想创建一个逻辑来检查每条记录的 id 是否已经存在于数据库中。如果它不存在,那么将有一个数据插入过程。如果已经存在,会有一个数据更新过程

我已经提出了逻辑。我只是想确定我的逻辑是否有效

我的逻辑代码是这样的:

$path = storage_path('data.json');
$json = json_decode(file_get_contents($path), true);
foreach ($json['value'] as $value) {
    $data = \DB::table('details')->where('id', '=', $value['Code'])->get();
    if ($data->isEmpty()) {
        \DB::table('details')->insert(
            [
                'id' => $value['Code'],
                'number' => $value['Number'],
                ...
            ]
        );
    }
    else {
        \DB::table('details')
            ->where('id', '=', $value['Code'])
            ->update([
                'id' => $value['Code'],
                'number' => $value['Number'],
                ...
            ]);
    }
}

代码正在运行。但过程似乎真的很漫长

您还有其他更好的解决方案吗?

标签: jsonlaravellaravel-5eloquentlaravel-5.6

解决方案


更新或创建

您可能还会遇到想要更新现有模型或创建新模型(如果不存在)的情况。Laravel 提供了一种updateOrCreate方法来一步完成。像firstOrCreate方法一样,updateOrCreate持久化模型,所以不需要调用 save()

// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
);

在您的情况下,您的代码应该是这样的(Details首先创建模型):

$path = storage_path('data.json');
$json = json_decode(file_get_contents($path), true);
foreach ($json['value'] as $value) {
    Details::updateOrCreate(
        [ 'id' => $value['Code'] ],
        [ 'number' => $value['Number'], ... ]
    );
}

推荐阅读