导入字段不一致的JSON到MySQL报未定义attachments属性如何修复
报错根因
解析JSON生成的stdClass对象在遇到无attachments字段的条目时,本身不存在该属性,直接读取$obj->attachments就会触发未定义属性的ErrorException。你创建的数据表中attachments字段本身配置为可空,天然适配这种字段缺失的场景,仅需在导入逻辑中对缺省值做兜底处理即可解决问题。
修复方案
- 方案1:保留原有stdClass解析逻辑,增加属性存在判断
在赋值时先判断条目是否包含attachments属性,存在则编码后存入,不存在则写入null适配数据库的可空字段定义,修改后的导入代码如下:
$json = File::get("database/your_posts_1.json"); $data = json_decode($json); foreach($data as $obj) { My_post::create([ 'attachments' => isset($obj->attachments) ? json_encode($obj->attachments) : null, 'timestamp' => $obj->timestamp, 'data' => json_encode($obj->data), 'title' => $obj->title ]); }
- 方案2:将JSON解析为关联数组,提升代码可读性
给json_decode传入第二个参数true,将解析结果转为PHP关联数组,从根源上避免stdClass对象未定义属性的报错,修改后的代码如下:
$json = File::get("database/your_posts_1.json"); // 第二个参数true表示将JSON解析为关联数组而非stdClass对象 $data = json_decode($json, true); foreach($data as $item) { My_post::create([ // 不存在attachments键时直接赋值null,匹配数据库可空字段定义 'attachments' => isset($item['attachments']) ? json_encode($item['attachments']) : null, 'timestamp' => $item['timestamp'], 'data' => json_encode($item['data']), 'title' => $item['title'] ]); }
注意:需避开一个常见逻辑误区:不要直接写
json_encode($item['attachments'] ?? null),这种写法会在无attachments字段时,将PHP的null值经json_encode处理为字符串"null"存入数据库,而非预期的SQL NULL空值。
- 额外校验提示
确认My_post模型的$fillable属性已包含上述四个需要批量赋值的字段,否则Laravel的批量赋值保护机制会拦截数据写入,导致导入失败,模型配置示例:
class My_post extends Model { protected $fillable = [ 'attachments', 'data', 'timestamp', 'title' ]; }
内容的提问来源于stack exchange,提问作者Dugonkt
相关产品推荐
相关产品推荐

