【问题标题】:Laravel 5.8 Save API data to DatabaseLaravel 5.8 将 API 数据保存到数据库
【发布时间】:2020-01-15 13:52:51
【问题描述】:

我想将来自第三方 api 的数据存储到我的数据库中,听起来很基本但我有点困惑。

我的控制器里有这个

public function showTips()
    {
        $client = new Client(['headers' => ['Accept' => 'application/json']]); 
        $res = $client->request('GET', 'https://example.com/api/xxx/xxxapiKey=xxxx');
        $data = json_decode($res->getBody()->getContents());
        $events = $data->Data;
        dd($events);
        //return view('tips')->with(compact('events'));               
    }

我得到的数据:

array:2 [▼
  0 => {#8824 ▼
    +"timeLive": "76"
    +"matchID": "10482C5"

我必须做哪些更改才能接收“timeLive”数据并将其存储在 MySQL 表中? 我们将不胜感激每一个帮助!

【问题讨论】:

  • 桌子长什么样?您要将timeLive 值存储在哪一列?
  • 我创建了一个表“ApiData”,其中包含字段:id、timevalue、...等
  • 什么是“...”?其他字段是否应该为空/NULL?
  • 其他api数据列较多,也应该为空/NULL

标签: mysql laravel api


【解决方案1】:

你应该像这样循环 foreach 结果:

$data = json_decode($res->getBody()->getContents(),true);
    $events = $data['Data'];
foreach($events as $item)
{
 DB::table('your_table')->insert(['timeLive'=>$item['timeLive']])
}

witch timeLive 是您的表“your_table”中的列

【讨论】:

  • 不能使用 stdClass 类型的对象作为数组
  • DB::table('your_table')->insert(['timeLive'=>$item->timeLive])
  • 我遇到了另一个错误:语法错误,意外的 ''timeLive'' (T_CONSTANT_ENCAPSED_STRING),需要标识符 (T_STRING) 或变量 (T_VARIABLE) 或 '{' 或 '$'
  • 它节省了!但现在的问题是当我请求 API 数据时它重复了!我的意思是表字段被一次又一次地创建。我还想要一个建议:“my_table”表数据必须与 Api 数据同时更新,我的意思是至少每分钟更新一次。我应该在我的视图控制器上使用这个代码吗?有什么建议吗?
  • 还有,这个项目怎么称呼? "homeTeamInfo": { "homeTeam": "GNK Dinamo Zagreb"
【解决方案2】:

以下将timeLive 值插入timevalue 列:

\DB::table('my_table')->insert(collect($events)->map(function($item) {
    return ['timevalue' => $item->timeLive];
}));

【讨论】:

    猜你喜欢
    • 2020-06-09
    • 2016-12-13
    • 1970-01-01
    • 2021-07-18
    • 2021-06-10
    • 2018-03-04
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    相关资源
    最近更新 更多