【问题标题】:how to insert the data from one json file to many table in laravel that have related data using updateOrCreate function?如何使用 updateOrCreate 函数将数据从一个 json 文件插入到 laravel 中具有相关数据的多个表中?
【发布时间】:2019-05-01 18:40:44
【问题描述】:

我有这样的json

[
    {
      "id": 11,
      "name": Tommy,
      "hobby": Football,

    },

    {
      "id": 22,
      "name": Timmy,
      "hobby": Basketball,

    }
]

我有两张桌子,一个人和一个爱好。

表有这样的列: 人表(id,name), 爱好表(id、person_id、hobby_name)

1个人有很多爱好

我想使用 updateOrCreate 函数将 json 数据插入到两个表中。我使用 updateOrCreate 方法,因为 Json 将每 5 秒更新一次数据。如果一个人不存在,我需要创建,如果这个人存在,我需要更新爱好。

问题:如何更新或创建这两个表?因为我现在只能使用 1 张桌子。

【问题讨论】:

标签: php json database laravel eloquent


【解决方案1】:

我假设您有 PersonHobby 模型,它们的关系已经到位。

由于您从 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']]
    );
}

【讨论】:

  • 之前谢谢,但是在这段代码中,我想我们无法检测到一个人有相同的 hobby_name。
  • $person->hobbies()->updateOrCreate(...) 首先检查 hobby_name 是否已经为那个人准备好了。如果它在那里,它将更新hobby_name,否则它将创建它。您是否先尝试过此代码?
  • 是的,我试过这段代码。有用。但我认为我提出这个问题是错误的,因为我在这种情况下给出了身份证。如果Json中没有id怎么办,id会使用自增生成。你怎么看?
  • 是的。但是你需要传递一些独特的东西来识别现有的记录。类似于此人的电子邮件。
猜你喜欢
  • 1970-01-01
  • 2015-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
  • 2015-01-20
  • 2013-11-08
相关资源
最近更新 更多