我在文件夹中有 json 文件,database\data\countries.json
并且有CountryTableSeeder.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']
));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句