繁体   English   中英

如何将JSON文件导入数据库

[英]How to import JSON file into database

我在文件夹database\\data\\countries.json有一个json文件,并且我有CountrysTableSeeder.php

我想将countries.json中的所有数据播种到表Country中。 但是发生错误Trying to get property of non-object

我已经执行了找到的步骤,但是仍然出现错误。

这是我的模型:

protected $fillable = ['country_name', 'iso_code'];

这是我的播种器代码:

public function run()
{
  $countryJson = File::get("database/data/countries.json");
  $data = json_decode($countryJson, true);
  foreach ($data as $obj) {
    Country::create(array(
      'country_name' => $obj->name, 'iso_code' => $obj->sortname
    ));
  }
}

您需要在foreach中传递相同的变量,并通过检查dd($ data)来确保您具有name元素; 并且您需要通过$ obj ['name']而不是通过$ obj-> name获取数组元素,因为它不是对象。

$data = json_decode($countryJson, true);
        foreach ($data['countries'] as $obj) {
            Country::create(array(
              'country_name' => $obj['name'], 'iso_code' => $obj['sortname']
              ));
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM