0 レビュー
0 回答
php-laravelでは、外部api jsonデータを1回だけ保存するために(重複を防ぐため)、前に確認したいのですが、テーブルは空ですか?
私は新しく、助けが必要です。外部のjsonapiデータリンクがあり、それらの配列/オブジェクトデータを保存したいのですが、一度だけ、テーブルが空かどうかを確認する必要があります.1つのデータまたは穴の存在を確認することで可能性があります。 100個のデータを何度も挿入するコードを実行すると、最終的には何十億もの同じデータになるからです。重複データの挿入を防ぐためのコードを作成すると、1つずつチェックされますが、プログラムの実行が遅くなるため、これは望ましくありません。コードも含めて、アイデアをお願いします。 Stackoverflowの優秀なエンジニアにとっては非常にシンプルだと思います。以下に、移行、モデル、およびコントローラーのすべてのコードを1つずつ示します。
移行テーブル:
Schema::create('apiposts', function (Blueprint $table) {
$table->integer('userId');
$table->integer('id');
$table->text('title');
$table->String('body');
$table->timestamps();
});
モデルクラス:
class apipost extends Model
{
use HasFactory;
protected $table = "apiposts";
protected $fillable = ['userId','id','title','body'];
}
コントローラークラス:
namespace App\Http\Controllers;
use App\Models\apipost;
use Illuminate\Support\Facades\Http;
class postController extends Controller
{
public function index()
{
$response = Http::get('https://jsonplaceholder.typicode.com/posts')->json();
if (!apipost::whereNull('userId')->exists()) {
foreach ($response as $post) {
apipost::create($post);
}
}
$alldata = apipost::Paginate(5);
return view('index',['alldata' => $alldata]);
}
}
コントローラーのコードを参照してください。コントローラクラスでは、 apipost::whereNull('userId')->exists()
が正しく機能していません。以下のコードも試しましたが、機能しませんでした:
if (apipost::where('userId', Input::get('userId'))->exists()) {
// exists
}
ここで、 Input は、VSCodeエディターのエラーを示しています。これは、間違いなく間違った解決策を意味します。
Schema::create('apiposts', function (Blueprint $table) {
$table->integer('userId');
$table->integer('id');
$table->text('title');
$table->String('body');
$table->timestamps();
});
モデルクラス:
class apipost extends Model
{
use HasFactory;
protected $table = "apiposts";
protected $fillable = ['userId','id','title','body'];
}
コントローラークラス:
namespace App\Http\Controllers;
use App\Models\apipost;
use Illuminate\Support\Facades\Http;
class postController extends Controller
{
public function index()
{
$response = Http::get('https://jsonplaceholder.typicode.com/posts')->json();
if (!apipost::whereNull('userId')->exists()) {
foreach ($response as $post) {
apipost::create($post);
}
}
$alldata = apipost::Paginate(5);
return view('index',['alldata' => $alldata]);
}
}
コントローラーのコードを参照してください。コントローラクラスでは、 apipost::whereNull('userId')->exists()
が正しく機能していません。以下のコードも試しましたが、機能しませんでした:
if (apipost::where('userId', Input::get('userId'))->exists()) {
// exists
}
ここで、 Input は、VSCodeエディターのエラーを示しています。これは、間違いなく間違った解決策を意味します。
わからない
同様の質問
私たちのウェブサイトで同様の質問で答えを見つけてください。