如何使最有效和最高效的逻辑来检查数据库中的数据是否存在?

How do I make the most effective and efficient logic to check the data in the database exist or not?

我用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'],
                ...
            ]);
    }
}

代码有效。但是过程好像真的很长

你有更好的解决方案吗?

我认为这是最好的方法。 Eloquent return 是一个集合,因此您不能只验证您的字符串是否为空。

updateOrCreate

如果 none 存在,您可能还会遇到想要更新现有模型或创建新模型的情况。 Laravel 提供了一种 updateOrCreate 方法来一步完成。与 firstOrCreate 方法一样,updateOrCreate 保留模型,因此无需调用 save():

// If there's a flight from Oakland to San Diego, set the price to .
// 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'], ... ]
    );
}