2017-05-17 13 views
4

別のサービスからJSONを取得していて、テーブルにデータの束を挿入したいとします。私はそれを実行するたびにクラッシュしないようにしたいと思います。私はテーブルの私のPKに私のユニークな制約を維持したいのですが(なぜ私は同じデータを2回挿入したくないのですが)、私はlaravelが致命的なエラーを発生させたくない(特定のテーブルのみ)。重複したキーを挿入するとエラーが無視されます

データを挿入して、重複する主キーを持つ別のデータを挿入しようとすると、挿入を続行するにはどうすればよいですか?

Schema::create('dummy', function (Blueprint $table) { 
    $table->integer('id')->unique(); 

    $table->string('name',100); 
}); 

別のAPIからJSONの束を取得します。次に、すべての行を挿入します。

{ 
    'id':1, 
    'name': 'one' 
},{ 
    'id':2 
    'name':'two' 
} 

です。

DB::table('dummy')->insert([ 
    ['id' => 1, 'name' => 'one'], 
    ['id' => 2, 'name' => 'two'] 
]); 

さらに、第三者APIに関する新しいデータがあります。そして、私のデータベースを更新する:

は、JSONを取得し、受信:

{ 
    'id':1, 
    'name': 'one' 
},{ 
    'id':2 
    'name':'two' 
},{ 
    'id':3 
    'name':'three' 
} 

作ること:

DB::table('dummy')->insert([ 
    ['id' => 1, 'name' => 'one'], // <-- will crash there cause PK already existe, but want to keep inserting 
    ['id' => 2, 'name' => 'two'], // <-- skipp cause already exist 
    ['id' => 3, 'name' => 'three'] // insert that line. 
]); 
+1

効率性のために、重複したキー更新のような重複を処理するカスタムクエリがあります。または、try {...} catch(\ Exception $ e){}内のテーブルにデータを挿入しているコードをラップすると、何かが間違っていました。 } – adelineu

+0

@tadman私はそれがはっきりしていましたが、 –

+1

それは具体的なことですが、問題を示す小さなコードスニペットを含めると、はっきりしています。 – tadman

答えて

1

あなたは、代わり

try 
{ 
    // inserting in DB; 
} 
catch(\Illuminate\Database\QueryException $e){ 
    // do what you want here with $e->getMessage(); 
} 

をPDOの例外をキャッチしようとしますDBトランザクションを試すことができます。

public function insertInDB() 
{ 
    DB::transaction(function() { 
     DB::table(...); 
     // if everything is fine, it will commit, else, it will rollback 
    } 
} 
関連する問題