我正在尝试从json api获取数据,并将返回的数组转换为模型的集合。因此api返回具有id和name字段的用户数组。当我将json转换为模型时,我得到了正确数量的元素,但是模型中的所有属性均为null。
我尝试同时使用水合物和填充模型以将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,
];
}
}
通话结束后,控制器将返回
{“ data”:[{“ id”:null,“ name”:null},{“ id”:null,“ name”:null}]}
json返回不为null的ID和名称
答案 0 :(得分:0)
我正在测试此代码,并且工作正常:
$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,
];