插入重复键时,laravel eloquent 忽略错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44013914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel eloquent ignore error when inserting a duplicate key
提问by PL Audet
I'm fetching a JSON from another service and want to insert a bunch of data in a table. I want to do it a way it won't crash everytime I run it. I'd like to keep my unique constraint on my PK of the table, (cause i dont want to insert the same data twice) but, I don't want laravel to throw a fatal error if it happens (on a specific table only).
我正在从另一个服务中获取 JSON 并想在表中插入一堆数据。我想以一种每次运行它都不会崩溃的方式来做。我想在我的表 PK 上保留我的唯一约束(因为我不想两次插入相同的数据)但是,我不希望 laravel 在发生这种情况时抛出致命错误(仅在特定表上) )。
How can I insert my datas, and continue to insert if I try to insert another data with a duplicate primary key?
如果我尝试插入另一个具有重复主键的数据,如何插入我的数据并继续插入?
Schema::create('dummy', function (Blueprint $table) {
$table->integer('id')->unique();
$table->string('name',100);
});
Fetch a bunch of JSON from another API. Then inserting all row:
从另一个 API 获取一堆 JSON。然后插入所有行:
{
'id':1,
'name': 'one'
},{
'id':2
'name':'two'
}
that makes.
这使得。
DB::table('dummy')->insert([
['id' => 1, 'name' => 'one'],
['id' => 2, 'name' => 'two']
]);
Then another day, there are new data on the 3rd party API. And want to update my database:
又过了一天,第 3 方 API 有了新数据。并想更新我的数据库:
fetch the json, and receives:
获取 json,并接收:
{
'id':1,
'name': 'one'
},{
'id':2
'name':'two'
},{
'id':3
'name':'three'
}
that makes :
这使得:
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.
]);
回答by Jared Dunham
Laravel's Query Builder now has insertOrIgnore
in version v5.8.33 and up:
Laravel 的 Query Builder 现在有insertOrIgnore
v5.8.33 及更高版本:
<?php
DB::table('users')->insertOrIgnore([
['id' => 1, 'email' => '[email protected]'],
['id' => 2, 'email' => '[email protected]']
]);
Read more here: https://laravel.com/docs/5.8/queries#inserts
在此处阅读更多信息:https: //laravel.com/docs/5.8/queries#inserts
回答by EddyTheDove
You may try catching PDO exception
您可以尝试捕获 PDO 异常
try
{
// inserting in DB;
}
catch(\Illuminate\Database\QueryException $e){
// do what you want here with $e->getMessage();
}
Alternatively, but not sure, you could try with DB transactions:
或者,但不确定,您可以尝试使用数据库事务:
public function insertInDB()
{
DB::transaction(function () {
DB::table(...);
// if everything is fine, it will commit, else, it will rollback
}
}
回答by arecaps
What you want is INSERT IGNORE
and that question already has been answered, see INSERT IGNORE using Laravel's Fluent
您想要的是INSERT IGNORE
并且该问题已经得到解答,请参阅使用 Laravel 的 Fluent 插入忽略