json - 如何制定最有效和最高效的逻辑来检查数据库中的数据是否存在?
问题描述
我使用 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'],
...
]);
}
}
代码正在运行。但过程似乎真的很漫长
您还有其他更好的解决方案吗?
解决方案
您可能还会遇到想要更新现有模型或创建新模型(如果不存在)的情况。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'], ... ]
);
}
推荐阅读
- sql-server - T-SQL 查询以获得所需的输出
- node.js - nixos中的nodejs headless-gl null
- python - 单击一个按钮以将输入字段保存在 Tkinter 中的 csv 文件中
- css - 在 hr 上对齐文本基线
- razor-pages - 使用 AddRazorRuntimeCompilation 时出现 CSS 隔离问题
- javascript - supbase 下载图像错误请求标头应具有必需的属性“授权”
- java - 如何检测用户是否输入分数
- java - 从 Gradle 中的依赖项中排除特定包
- rust - 是否可以从同一结构中展平多个排水迭代器?
- reactjs - MUI 5 自动完成过滤选项计数