[英]how to insert the data from one json file to many table in laravel that have related data using updateOrCreate function?
我有這樣的json
[
{
"id": 11,
"name": Tommy,
"hobby": Football,
},
{
"id": 22,
"name": Timmy,
"hobby": Basketball,
}
]
我有2張桌子,人和愛好。
表格具有這樣的列:人員表(id,名稱),興趣表(id,person_id,hobby_name)
1個人有很多愛好
我想使用updateOrCreate函數將json數據插入到兩個表中。 我使用updateOrCreate方法,因為Json將每5秒更新一次數據。 我需要創建一個人是否不存在,如果該人存在,則需要更新興趣愛好。
問題:如何更新或創建兩個表? 因為我現在只能使用1個表。
我認為您已經建立了Person
& Hobby
模型及其關系。
由於您是從json獲取人員ID的,因此請確保Person
模型在$fillable
id
為
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']]
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.