【问题标题】:Store API JSON response in SQL Database在 SQL 数据库中存储 API JSON 响应
【发布时间】:2020-01-07 18:24:23
【问题描述】:

希望将来自外部 API(使用 Guzzle)的 JSON 响应存储到 mySQL 数据库中。到目前为止我所做的很多事情都是基于这个问题/答案

Storing parts of API data to database

我有一个模型、控制器和迁移设置。计划是设置一个每天运行并从 API 调用新数据的 CRON 作业。

现在,我只想将数据存储到数据库中(我可以稍后设置 CRON 作业)。

我在这里遗漏了什么或我的代码中有任何错误吗?我之前有过路线设置,但不知道是否适用?

**编辑

运行此程序时,数据库中没有存储任何内容。

型号

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Rating extends Model
{

    protected $fillable = ['ratingId', 'ratingName', 'ratingKey', 'ratingKeyName', 'schemeTypeId'];

}

控制器

我这里有两个函数。首先是使用外部 API。第二个功能是将其存储到数据库中。

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use GuzzleHttp\Client;
use App\Rating;


class GuzzleController extends Controller
{
    public function getRatings()
    {
        $client = new Client([
            'url' => 'https://api.ratings.food.gov.uk/ratings'
        ]);
        $request = $client->request('GET', [
            'headers' => [
                'x-api-version' => '2',
                'Accept'        => 'application/json'
            ]
        ]);

        $ratings = json_decode($request->getBody()->getContents(), true);
        return $ratings;

    }

    public function saveRatings()
    {
        $ratings = $this->getRatings();

        collect($ratings)
            ->each(function($rating, $key) {
                Rating::create([
                    'ratingid' => $rating['ratingid'],
                    'ratingName' => $rating['ratingName'],
                    'ratingKey' => $rating['ratingKey'],
                    'ratingKeyName' => $rating['ratingKeyName'],
                    'ratingTypeId' => $rating['ratingTypeId']
                ]);
            });

    }
}

迁移

只是在这里设置桌子。

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRatingsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('ratings', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('ratingId');
            $table->string('ratingName');
            $table->string('ratingKey');
            $table->string('ratingKeyName');
            $table->integer('schemeTypeId');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('ratings');
    }
}

【问题讨论】:

  • 到底是什么问题?您遇到了什么错误?
  • 嘿@CaddyDZ,更新了对此的描述。但是我的数据库表仍然是空的。我需要运行某个 Artisan 命令吗?或任何检查错误的方法。
  • 使用 dd() 缩小问题范围,例如在 Rating::create([]) 完成后检查并查看结果
  • 或者this是原因
  • @HussamAdil 谢谢你会试一试!

标签: php mysql laravel api guzzle


【解决方案1】:

我发现你犯了几个小错误。

public function saveRatings()
    {
        $ratings = $this->getRatings();

        collect($ratings)
            ->each(function($rating, $key) {
                Rating::create([
                    'ratingId' => $rating['ratingId'],
                    'ratingName' => $rating['ratingName'],
                    'ratingKey' => $rating['ratingKey'],
                    'ratingKeyName' => $rating['ratingKeyName'],
                    'schemeTypeId' => $rating['schemeTypeId']
                ]);
            });
    }

'ratingTypeId' =&gt; $rating['ratingTypeId']这是在你的函数中,但在迁移中你有$table-&gt;integer('schemeTypeId');

您的 Guzzle 请求对我不起作用。这是我的版本。

public function getRatings()
    {
        $url = 'https://api.ratings.food.gov.uk/ratings';

        $client = new Client(['headers' => [
            'x-api-version' => '2',
            'Accept'        => 'application/json'
        ]]);

        $request = $client->request('GET', $url);
        $ratings = json_decode($request->getBody()->getContents(), true);

        return $ratings['ratings'];
    }

【讨论】:

  • 嘿迪诺!好地方,感谢您修改请求!我将如何一次性测试它以查看它是否存储在数据库中?是否有任何工匠命令可以使用,或者我需要设置路线吗?
  • 不用担心。是的,您可以创建一个简单的 get 路由到 saveRatings(),然后在浏览器中点击它。但是,由于您打算将它与 CRON 一起使用,因此您现在可以创建一个命令并使用 artisan 调用它。
  • Dino 非常感谢您的帮助,得到它的工作伙伴!我会尝试使用 CRON,但如果遇到任何问题,我会发布另一个问题。
  • 每次我点击浏览器时,它都会存储每次请求(导致重复)。我可以修改控制器上的某些内容,使其仅添加新条目并更新现有条目吗?
  • 一切顺利!找到解决它的 ::updateOrCreate 。谢谢!
猜你喜欢
  • 2022-01-06
  • 2022-07-26
  • 1970-01-01
  • 2020-01-11
  • 2021-06-26
  • 2019-06-29
  • 2012-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多