我正在通过laravel使用带有Guzzle的API,并将响应存储到数据库中。
我已经成功地存储了JSON响应的“评级”部分。但是现在我想添加“元”-“提取日期”。
要使它正常工作,我需要更改什么?
以下是我正在使用的JSON API响应,以及我用来保存到数据库中的一部分控制器。
使用laravel 7.0
**JSON from API**
{
"ratings": [
{
"ratingId": 12,
"ratingName": "5",
"ratingKey": "fhrs_5_en-gb",
"ratingKeyName": "5",
"schemeTypeId": 1,
"links": [
{
"rel": "self",
"href": "http://api.ratings.food.gov.uk/ratings/12"
}
]
}
],
"meta": {
"dataSource": "API",
"extractDate": "2020-06-29T21:24:43.820107+01:00",
"itemCount": 11,
"returncode": "OK",
"totalCount": 11,
"totalPages": 1,
"pageSize": 11,
"pageNumber": 1
}
}
**controller snippet**
$client = $this->client();
$request = $client->request('GET', 'https://api.ratings.food.gov.uk/ratings');
$ratings = json_decode($request->getBody()->getContents(), true);
collect($ratings['ratings'])
->each(function($rating, $key) {
Rating::updateOrCreate([
'ratingId' => $rating['ratingId'],
'ratingName' => $rating['ratingName'],
'ratingKey' => $rating['ratingKey'],
'ratingKeyName' => $rating['ratingKeyName'],
'schemeTypeId' => $rating['schemeTypeId'],
'extractDate' => $rating['extractDate']
]);
});
编辑-附加信息
如果我错了,请纠正我,但是目前,我认为该集合只能保存“评分”对象的内容。我试图从收集行中删除对象,并将每行修改为:
'ratingId' => $rating['rating']['ratingId'],
'extractDate' => $rating['meta']['extractDate']
但是我得到“未定义的索引:评分”
$ ratings的DD
array:3 [▼
"ratings" => array:11 [▼
0 => array:6 [▼
"ratingId" => 12
"ratingName" => "5"
"ratingKey" => "fhrs_5_en-gb"
"ratingKeyName" => "5"
"schemeTypeId" => 1
"links" => array:1 [▶]
]
1 => array:6 [▶]
2 => array:6 [▶]
3 => array:6 [▶]
4 => array:6 [▶]
5 => array:6 [▶]
6 => array:6 [▶]
7 => array:6 [▶]
8 => array:6 [▶]
9 => array:6 [▶]
10 => array:6 [▶]
]
"meta" => array:8 [▼
"dataSource" => "API"
"extractDate" => "2020-06-29T22:56:04.250649+01:00"
"itemCount" => 11
"returncode" => "OK"
"totalCount" => 11
"totalPages" => 1
"pageSize" => 11
"pageNumber" => 1
]
"links" => array:1 [▶]
]
答案 0 :(得分:0)
您没有任何这样的数据结构:
'ratingId' => $rating['rating']['ratingId']
您的钥匙中没有“待定”的钥匙。
你有
'ratingId' => $ratings['ratings'][$idx]['rating_id']
我想你想要的是
collect($ratings['ratings'])
->each(function($rating, $key) use ($ratings) {
Rating::updateOrCreate([
'ratingId' => $rating['ratingId'],
'ratingName' => $rating['ratingName'],
'ratingKey' => $rating['ratingKey'],
'ratingKeyName' => $rating['ratingKeyName'],
'schemeTypeId' => $rating['schemeTypeId'],
'extractDate' => $ratings['meta']['extractDate']
]);
});
我的原始评论基于您的问题:)