首页 > 解决方案 > 如何使用 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 张桌子。

标签: phpjsondatabaselaraveleloquent

解决方案


我假设你有Person&Hobby模型与他们的关系到位。

由于您从 json 获取人员 ID,请确保Person模型id$fillableas

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']]
    );
}

推荐阅读