Laravel 8雄辩的插入新记录



我正在尝试理解Laravel 8的新功能upsert

下面是我的示例表:

flights
id (primary key and auto Inc)
departure
destination
price

在我的代码:

AppModelsFlight::upsert([
['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], ['departure', 'destination']);

这是来自Laravel文档的样例表,它有一个键id。

如果departuredestination都匹配,我想更新记录,但这些字段不是唯一的。

每次运行代码时,它都会插入一条新记录,但不会更新。如何使upsert工作?

我是否需要使departuredestination唯一,或者不使它们唯一就可以工作?

另外,如果我需要使两个字段唯一,那么我如何在迁移中做到这一点?

我遇到了同样的问题,我将第二个参数设置为" composite unique "。

添加到迁移

$table->unique(['departure','destination']); 

问题应该解决

文档

从Laravel 9开始。更新了Eloquent文档页面,以提及upsert()依赖于DB唯一约束:

除SQL Server外的所有数据库都要求upsert方法第二个参数中的列具有"primary"或";unique"索引。此外,MySQL数据库驱动程序忽略upsert方法的第二个参数,并始终使用"primary"one_answers";unique"用于检测现有记录的表索引。

我认为您需要在upsert的第二个参数中传递唯一键,这是表的id列和主键,示例数据将是

AppModelsFlight::upsert([
['id'=> 1, 'departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
['id'=> 2, 'departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], ['id']);

要更新的列需要第三个参数

Flight::upsert([
['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], ['departure', 'destination'], ['price']);

最新更新