首页 > 解决方案 > PHP(Laravel) 存储类对象

问题描述

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

JSON数据

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

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

$object = new Product();

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


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

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

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

标签: phpjsonlaravelguzzle

解决方案


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

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

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


推荐阅读