我检查数据库中数据的逻辑是否有效?

Is my logic to check data in database efficient?

我用laravel 5.6

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

逻辑我搞定了。我只是想确定我的逻辑是否有效

我的逻辑代码是这样的:

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

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

你有更好的解决方案吗?

更新

我找到另一个解决方案使用 updateOrCreate

我这样试:

$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'], 'last_modified_at' => $last_modified_date, ... ]
    );
}

你怎么看?

您不能在 updateOrCreate

中使用 <>

希望这段代码能帮到你:

$path = storage_path('data.json');
$json = json_decode(file_get_contents($path), true);
foreach ($json['value'] as $value) {
    $detail = Details::firstOrCreate(
        [ 'id' => $value['Code'] ],
        [ 'number' => $value['Number'], 'last_modified_at' => $last_modified_date, ... ]
    );
    if($detail->last_modified_at != $last_modified_date) {
        $detail->update([
            'number' => $value['Number'],
            'last_modified_at' => $last_modified_date,
            ...
        ]);
    }
}