【问题标题】:PHP(Laravel) storing class objectPHP(Laravel) 存储类对象
【发布时间】:2020-06-22 06:24:54
【问题描述】:

我正在使用 guzzle 包从 API 接收 JSON 数据。我要存储在数据库中的接收数据:

JSON data

我的数据保存到数据库代码:

$contents = json_decode($response->getBody());

$object = new Product();

$object->GeneralInfo = $contents->data->GeneralInfo;
    $object->save();


    return response()->json($contents);

我收到的异常:stdClass 类的对象无法转换为字符串

我知道它想要存储正在传递的字符串和对象。存储这些数据的最佳方式是什么?转换为数组可能吗?提前感谢您的提示。

【问题讨论】:

  • 您可以尝试将其添加到您的 json_decode 行$contents = json_decode($response->getBody(), true)
  • 试过了,它设置了对数组的响应,对吧?然后我得到'试图获取非对象的属性'数据''错误

标签: php json laravel guzzle


【解决方案1】:

来自内容的一般信息是对象。当 laravel 尝试将其插入数据库时​​,它会尝试将数组转换为字符串。因此,当它获取对象时,它无法将其转换为字符串。

将您的响应正文解码为数组: $contents = json_decode($response->getBody(), true);

然后从数组中获取数据: $object->GeneralInfo = $contents['data']['GeneralInfo'];

【讨论】:

  • 获取参数 1 传递给 Illuminate\Database\Grammar::parameterize() 必须是数组类型,字符串给定。我觉得这很奇怪,因为响应已设置为数组。
  • 转储你从$contents['data']['GeneralInfo']得到的东西
  • 数组符合预期
  • 您是否在模型中为列 'GeneralInfo' 设置了 $cast ? protected $casts = ['GeneralInfo' => 'array'];
  • 我以前没有,但确实有帮助,非常感谢,先生。
猜你喜欢
  • 2014-12-31
  • 2018-12-03
  • 2010-09-13
  • 1970-01-01
  • 2018-08-10
  • 2017-12-06
  • 2012-01-26
  • 2016-03-10
相关资源
最近更新 更多