且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-08 08:25:04

您可以通过获取所有匹配项数据,然后使用收藏。

You can achieve this by getting all matches data and then looping through each one using a collection.

可以创建收藏集使用 collect()帮助器从数组数据中删除。

Collections can be created from array data using the 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()函数(用于运行耗时调用)。

With this code, we call the saveMatches() function, which calls the getMatches() function (used to run the guzzle call).

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

Then, for each match, we save a new record to the database use the Match facade.

注释


  • 如上所述,***创建团队模型,因此您可以根据团队识别和调用比赛。

  • 请确保调用 $ fillable $ guarded 类变量在您的 Match 模型中,以便能够存储数据(请参阅此处)。

  • As mentioned above, it may be best to create a Team model, so you are able to identify and call matches based on teams.
  • Make sure to call the $fillable or $guarded class variable in your Match model to be able to store data (see here).

要在作业中使用此功能,首先需要使用

To use this functionality in a job, you first need to create a job using

php artisan make:job <job name>

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

For example, the job could be called CreateMatches. This will be located in app/Jobs/CreateMatches.php.

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

There you will see a handle() function, which is used to call any functionality within it once the job has fired.

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

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

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

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

You can then call the job, anywhere in your application logic using either CreateMatches::dispatch() or by using dispatch(new CreateMatches()) (don't forget to use the class at the top of your file).