Storing parts of API data to database

泄露秘密 提交于 2020-01-24 21:37:05

问题


Goal: I want to retrieve all the upcoming soccer matches for the upcoming week from a RESTful API. Once I get this data I would like to store the result in my database.

What I want to store: 'id', 'homeTeam', 'awayTeam', 'utcDate'. I want to do this for every match, so all the arrays in 'matches'

How my API result looks:

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 [▶]
 ]
]

I use Guzzle for doing this API request:

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);
    }
}

I created a model 'Match' and added a migration:

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

The migration:

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

Any tips on how to store this data to my database on the match model?


回答1:


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

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']
                ]);
            });
    }
}

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

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

Notes

  • 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).

Update

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

php artisan make:job <job name>

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

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
}

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).



来源:https://stackoverflow.com/questions/52870496/storing-parts-of-api-data-to-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!