Php 将部分API数据存储到数据库
目标:我想从RESTful API检索下一周所有即将到来的足球比赛。一旦我得到这些数据,我想把结果存储在我的数据库中 我要存储的内容:Php 将部分API数据存储到数据库,php,database,laravel,rest,guzzle,Php,Database,Laravel,Rest,Guzzle,目标:我想从RESTful API检索下一周所有即将到来的足球比赛。一旦我得到这些数据,我想把结果存储在我的数据库中 我要存储的内容:'id',homeTeam',awayTeam',utcDate'。我想对每个匹配都这样做,所以中的所有数组都是“匹配的” 我的API结果的外观: array:4 [▼ "count" => 10 "filters" => array:1 [▶] "competition" => array:6 [▶] "matches" => array
'id',homeTeam',awayTeam',utcDate'
。我想对每个匹配都这样做,所以中的所有数组都是“匹配的”
我的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);
}
}
我创建了一个模型“匹配”,并添加了一个迁移:
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');
});
}
移民:
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');
});
}
有关如何将此数据存储到匹配模型上的我的数据库中的任何提示?您可以通过获取所有匹配数据,然后使用 可以使用帮助器从数组数据创建集合 使用此代码,我们调用
saveMatches()
函数,该函数调用getMatches()
函数(用于运行guzzle调用)
然后,对于每个匹配,我们使用match
facade将一条新记录保存到数据库中
注释
- 如上所述,最好创建一个
模型,这样您就能够根据团队识别和调用匹配项团队
- 确保在
模型中调用Match
或$filleble
类变量,以便能够存储数据()$guarded
php artisan make:job <job name>
然后,您可以使用
CreateMatches::dispatch()
或使用dispatch(newcreatematches())
(不要忘记使用文件顶部的类)。作为起点,您可能想要一个名为teams的模型?因此,在您的匹配模型中,您将有match->hasMany团队,或者有一个homeTeam通过团队。在我的项目中放置这些功能的最佳位置是哪里?在控制器中执行此操作将在浏览器视图中返回完整的api调用,(返回json_decode($res->getBody()->getContents(),true);
)我希望在后台执行此操作,并根据数据库结果加载视图。@Dax您可以将此设置为在后台运行的命令。作为作业
或作为事件
。我想找一份工作
,你想让我更新答案吗?那将非常有用。更新后,示例已缩短。因此,您可以使用我在回答前面添加的代码。我认为collect()帮助程序工作不正常,我将函数添加到了我的作业中,当我运行它时,Laravel向我抛出以下错误:QLSTATE[23000]:完整性约束冲突:1048列“homeTeam”不能为null(SQL:insert into
MATCHS`)(homeTeam
,awayTeam
,在
更新,在
创建)值(,2018-10-18 10:53:252018-10-18 10:53:25))
,这些字段没有值