Php 插入重复密钥时发生laravel eloquent ignore错误
我正在从另一个服务获取JSON,并希望在表中插入一组数据。我想以一种不会每次运行都崩溃的方式运行它。我希望在表的PK上保留我的唯一约束(因为我不想插入相同的数据两次),但是,如果发生致命错误,我不希望laravel抛出致命错误(仅在特定表上) 如果我尝试插入另一个具有重复主键的数据,如何插入数据并继续插入Php 插入重复密钥时发生laravel eloquent ignore错误,php,mysql,laravel,eloquent,Php,Mysql,Laravel,Eloquent,我正在从另一个服务获取JSON,并希望在表中插入一组数据。我想以一种不会每次运行都崩溃的方式运行它。我希望在表的PK上保留我的唯一约束(因为我不想插入相同的数据两次),但是,如果发生致命错误,我不希望laravel抛出致命错误(仅在特定表上) 如果我尝试插入另一个具有重复主键的数据,如何插入数据并继续插入 Schema::create('dummy', function (Blueprint $table) { $table->integer('id')->unique();
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.
]);
DB::table('dummy')->insert([
['id'=>1,'name'=>'one'],//2,'name'=>'two'],//3,'name'=>'twree']//插入该行。
]);
您可以尝试捕获PDO异常
try
{
// inserting in DB;
}
catch(\Illuminate\Database\QueryException $e){
// do what you want here with $e->getMessage();
}
或者,但不确定,您可以尝试使用DB事务:
public function insertInDB()
{
DB::transaction(function () {
DB::table(...);
// if everything is fine, it will commit, else, it will rollback
}
}
您需要的是
INSERT IGNORE
,这个问题已经得到了回答,请参见Laravel的查询生成器现在在v5.8.33及更高版本中提供了insertOrIgnore
:
为了提高效率,您可以提出一个处理重复项的自定义查询(如重复密钥更新)。或者将插入表中数据的代码片段包装为try{…}catch(\Exception$e){//出错。}@tadman I虽然很清楚这有点特殊,但如果包含一小段代码来演示问题,那就非常清楚了。@tadman更新了OPT,它用非常精确的术语来描述问题。美好的是否可以将此应用于模型为createOrIgnore()的模型?在你说使用first或create之前,它的种族条件适用性很差。谢谢@Jared