php - PHP(Laravel) 存储类对象
问题描述
我正在使用 guzzle 包从 API 接收 JSON 数据。我要存储在数据库中的接收数据:
我的数据保存到数据库代码:
$contents = json_decode($response->getBody());
$object = new Product();
$object->GeneralInfo = $contents->data->GeneralInfo;
$object->save();
return response()->json($contents);
我收到的异常:stdClass 类的对象无法转换为字符串
我知道它想要存储正在传递的字符串和对象。存储这些数据的最佳方式是什么?转换为数组可能吗?提前感谢您的提示。
解决方案
来自内容的一般信息是对象。当 laravel 尝试将其插入数据库时,它会尝试将数组转换为字符串。因此,当它获取对象时,它无法将其转换为字符串。
将您的响应正文解码为数组:
$contents = json_decode($response->getBody(), true);
然后从数组中获取数据:
$object->GeneralInfo = $contents['data']['GeneralInfo'];
推荐阅读
- javascript - 当组件未在其中呈现时,如何在空 div 中显示消息?
- node.js - 在 node-sass 上安装期间在 Python 37-32 中出现命令失败
- jenkins - 如果下游作业中的构建失败,如何向在 Jenkins 中触发上游作业的用户发送电子邮件
- firebase - 初始化 Firebase 会引发错误 - Flutter
- r - 从 for 循环绘图
- node.js - child_process.exec ffmpeg 无限期挂起
- javascript - 扩展所有工作表的搜索范围
- node.js - Bookshelf.js 中的条件
- javascript - 前后端共享类型定义
- meteor - 如何下载 Meteor Galaxy 上的所有日志