php - 转换 Guzzle 响应 t Laravel 模型
问题描述
我正在尝试从 json api 获取数据并将返回的数组转换为模型集合。所以 api 返回一个带有 id 和 name 字段的用户数组。当我将 json 转换为模型时,我得到了正确数量的元素,但模型中的所有属性都是空的。
我尝试使用水合物和填充模型将 json 转换为模型。
$client = new Client(); //GuzzleHttp\Client
$request = new \GuzzleHttp\Psr7\Request('GET', 'https://test.com/users');
$json = $client->sendAsync($request)->then(
function ($response) {
return $response->getBody()->getContents();
}, function ($exception) {
return $exception->getMessage();
}
)->wait();
$object = (array)json_decode($json);
$collection = User::hydrate($object);
return UserResource::collection($collection);
class UserResource extends JsonResource
{
public static $wrap = null;
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->name,
'name' => $this->nameCombo,
];
}
}
调用完成后,控制器返回
{"数据":[{"id":null,"name":null},{"id":null,"name":null}]}
json 返回不为空的 id 和名称
解决方案
我正在测试这段代码并且工作得很好:
$client = new Client(); //GuzzleHttp\Client
$request = new \GuzzleHttp\Psr7\Request('GET', 'https://jsonplaceholder.typicode.com/users');
$json = $client->sendAsync($request)->then(
function ($response) {
return $response->getBody()->getContents();
}, function ($exception) {
return $exception->getMessage();
}
)->wait();
$object = (array)json_decode($json);
$collection = User::hydrate($object);
return UserResource::collection($collection);
class UserResource extends JsonResource
{
public static $wrap = null;
/**
* Transform the resource into an array.
*
* @return array
*/
public function toArray()
{
return [
'id' => $this->id,
'name' => $this->name,
];
}
}
你确定这部分是正确的吗?
return [
'id' => $this->name,
'name' => $this->nameCombo,
];
推荐阅读
- java - 在 java ( Android ) 中实例化接口
- java - 如何使用 try catch 来避免抛出异常?
- python - 在线程 Python 中构造类
- python-3.x - 执行中间人攻击时出现 Scapy 错误
- jquery - 无法在进行 ajax 调用时触发成功或失败事件
- python-3.x - 如何将包含重复字母的单词还原为其原始英文形式?
- node.js - 按需运行后台 Nodejs docker 服务(通过 Gitlab CI ??)
- llvm - 运行 LLVM 优化器会将 32 位内存访问转换为 64 位。有没有办法避免这种情况?
- asp.net-core-mvc - .NET Core MVC 中文件输入的远程验证
- java - 从 ArrayList 中的 HashMap 获取键和值