php - 如何使用 updateOrCreate 函数将数据从一个 json 文件插入到 laravel 中具有相关数据的多个表中?
问题描述
我有这样的json
[
{
"id": 11,
"name": Tommy,
"hobby": Football,
},
{
"id": 22,
"name": Timmy,
"hobby": Basketball,
}
]
我有 2 张桌子,人和爱好。
表有这样的列:人员表(id,name),爱好表(id,person_id,hobby_name)
1人有很多爱好
我想使用 updateOrCreate 函数将 json 数据插入到两个表中。我使用 updateOrCreate 方法,因为 Json 将每 5 秒更新一次数据。如果一个人不存在,我需要创建,如果这个人存在,我需要更新爱好。
问题:如何更新或创建这两个表?因为我现在只能使用 1 张桌子。
解决方案
我假设你有Person
&Hobby
模型与他们的关系到位。
由于您从 json 获取人员 ID,请确保Person
模型id
在$fillable
as
protected $fillable = ['id', 'name'];
现在您可以更新或创建人员及其爱好
$json = '[
{
"id": 11,
"name": "Tommy",
"hobby": "Football"
},
{
"id": 22,
"name": "Timmy",
"hobby": "Basketball"
}
]';
//convert json into associative array
$data = json_decode($json, true);
foreach ($data as $item) {
// find the person with the id or create the person with the given id
$person = \App\Person::updateOrCreate(['id' => $item['id']], $item);
// update person's hobby or create the hobby for that person
$person->hobbies()->updateOrCreate(
['person_id' => $item['id']],
['hobby_name' => $item['hobby']]
);
}
推荐阅读
- r - 参数值能否取决于 rmarkdown 输出格式?
- python - Python正则表达式否定
- javascript - 万事达卡支付网关 (MPGS) 中的支付会话超时如何工作?
- json - 如何将 JSON 输出格式化为 PowerShell 中的 Format-Table 网格
- xslt - Biztalk XSLT1.0 使用变量值
- flutter - setstate 不适用于 showdialog 和 alertdialog
- powerbi - Dateadd 查找上个月的总数
- security - 如何安全地允许 Github Actions 检查 PR 并在评论中发布结果
- css - CSS ::before 伪元素不尊重 z-index 堆叠上下文
- vue.js - 使用 vuex 的列表搜索栏