php - 将部分API数据存储到数据库

标签 php database laravel rest guzzle

目标:我想从 RESTful API 检索下周所有即将举行的足球比赛。一旦我得到这些数据,我想将结果存储在我的数据库中。

我要存储的内容:'id'、'homeTeam'、'awayTeam'、'utcDate'。我想对每场比赛都执行此操作,因此 'matches'

中的所有数组

我的 API 结果如何:

array:4 [▼
"count" => 10
"filters" => array:1 [▶]
"competition" => array:6 [▶]
"matches" => array:10 [▼
0 => array:12 [▼
  "id" => 233107
  "season" => array:4 [▶]
  "utcDate" => "2018-10-20T11:30:00Z"
  "status" => "SCHEDULED"
  "matchday" => 9
  "stage" => "REGULAR_SEASON"
  "group" => "Regular Season"
  "lastUpdated" => "2018-10-07T19:02:21Z"
  "homeTeam" => array:2 [▼
    "id" => 61
    "name" => "Chelsea FC"
  ]
  "awayTeam" => array:2 [▼
    "id" => 66
    "name" => "Manchester United FC"
  ]
  "score" => array:6 [▶]
  "referees" => []
]
1 => array:12 [▶]
2 => array:12 [▶]
3 => array:12 [▶]
4 => array:12 [▶]
5 => array:12 [▶]
6 => array:12 [▶]
7 => array:12 [▶]
8 => array:12 [▶]
9 => array:12 [▶]
 ]
]

我使用 Guzzle 来执行此 API 请求:

class GuzzleController extends Controller {
    public function getMatches() {
        $client = new Client();
        $uri = 'http://api.football-data.org/v2/competitions/PL/matches/?matchday=9&season=2018&matches';
        $header = ['headers' => ['X-Auth-Token' => 'My-Token']];
        $res = $client->get($uri, $header);
        $array = json_decode($res->getBody()->getContents(), true);
        dd($array);
    }
}

我创建了一个模型“Match”并添加了迁移:

class Match extends Model {
    // What code here?
}

迁移:

public function up() {
    Schema::create('matches', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->integer('match_id');
        $table->string('homeTeam');
        $table->string('awayTeam');
    });
}

有关如何将此数据存储到匹配模型上的数据库的任何提示?

最佳答案

您可以通过获取所有匹配数据,然后使用 collection 循环遍历每个数据来实现此目的。 .

可以使用 collect() 从数组数据创建集合 helper 。

class GuzzleController extends Controller
{
    public function getMatches()
    {
        $client = new Client();
        $uri = 'http://api.football-data.org/v2/competitions/PL/matches/?matchday=9&season=2018&matches';
        $header = ['headers' => ['X-Auth-Token' => 'My-Token']];
        $res = $client->get($uri, $header);
        $data = json_decode($res->getBody()->getContents(), true);
        return $data['matches'];
    }

    public function saveMatches()
    {
        $matches = $this->getMatches();

        collect($matches)
            ->each(function ($match, $key) {
                Match::create([
                    'match_id' => $match['id'],
                    'homeTeam' => $match['homeTeam']['name'],
                    'awayTeam' => $match['awayTeam']['name']
                ]);
            });
    }
}

使用此代码,我们调用 saveMatches() 函数,该函数又调用 getMatches() 函数(用于运行 guzzle 调用)。

然后,对于每个匹配,我们使用 Match 外观将新记录保存到数据库中。

注释

  • 如上所述,最好创建一个团队模型,以便您能够根据团队识别和调用匹配。
  • 确保在 Match 模型中调用 $fillable$guarded 类变量,以便能够存储数据 ( see here )。

更新

要在作业中使用此功能,您首先需要使用以下命令创建作业

php artisan make:job <job name>

例如,该作业可以称为 CreateMatches。该文件位于 app/Jobs/CreateMatches.php 中。

在那里您将看到一个 handle() 函数,该函数用于在作业触发后调用其中的任何功能。

public function handle()
{
    $this->saveMatches();
}

public function saveMatches()
{
    // Code goes here
}

public function getMatches()
{
    // Code goes here
}

然后,您可以使用 CreateMatches::dispatch() 或使用 dispatch(new CreateMatches()) 在应用程序逻辑中的任何位置调用作业(不要这样做)不要忘记使用文件顶部的类)。

关于php - 将部分API数据存储到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52870496/

相关文章:

php - 我的php和mysql程序有问题吗?

php - 无法将大于 500kb 的视频文件大小上传到 Android 中的 Linux 服务器

php - 项目推荐的数据库管理

java - android平台sqlite数据库的可扩展访问

join - Laravel Eloquent 地从联接表中选择了最新的行

php - Laravel 没有检测到我的本地(开发)数据库配置文件

php - 为 Laravel 中的每个 Controller 和方法创建一个路由

php 只检索数字,即使是字符串

php - 解析 url 的最后一个子串

php - 按日期分组观看电影