rits-tecnologia/eloquent-insert-on-conflict

用于 Eloquent 的 INSERT ON CONFLICT 宏

v1.0.1 2020-04-09 14:39 UTC

This package is auto-updated.

Last update: 2024-09-10 00:05:43 UTC


README

此包提供宏,用于在 Laravel 的 ORM Eloquent 中对具有 PostgreSQL 的模型运行 INSERT ... ON CONFLICT DO NOTHING 或 DO UPDATE SET 查询。

安装

使用 composer 安装此包。

composer require rits-tecnologia/eloquent-insert-on-conflict

如果您尚未使用包自动发现,请将服务提供者添加到 config/app.php 中的包服务提供者中。

InsertOnConflict\InsertOnConflictServiceProvider::class,

用法

模型

从模型中调用 insertOnConflict 并传递一个包含要插入其表的数组数据。

$data = [
    ['id' => 1, 'name' => 'name1', 'email' => 'user1@email.com'],
    ['id' => 2, 'name' => 'name2', 'email' => 'user2@email.com'],
];

User::insertOnConflict($data);

自定义 ON CONFLICT DO UPDATE 子句

仅更新特定列

如果您只想更新特定列,请将它们作为第二个参数传递。

User::insertOnConflict([
    'id'    => 1,
    'name'  => 'new name',
    'email' => 'foo@gmail.com',
], ['name'], 'do update set', 'id');
// The name will be updated but not the email.
使用自定义值更新

您可以通过传递关联数组来自定义当行已存在时列将被更新的值。

在以下示例中,如果 id = 1 的用户不存在,它将被创建,名称为 'created user'。如果它已存在,则名称将被更新为 'updated user'。

User::insertOnConflict([
    'id'    => 1,
    'name'  => 'created user',
], ['name' => 'updated user'], 'do update set', 'id');

生成的 SQL 是

INSERT INTO `users` (`id`, `name`) VALUES (1, "created user") ON CONFLICT (id) DO UPDATE SET `name` = "updated user"

您可以在第二个参数中结合键值对和列名,以指定使用自定义文字或表达式或默认的 VALUES(column) 更新的列。例如

User::insertOnConflict([
    'id'       => 1,
    'name'     => 'created user',
    'email'    => 'new@gmail.com',
    'password' => 'secret',
], ['name' => 'updated user', 'email'], 'do update set', 'id');

将生成

INSERT INTO `users` (`id`, `name`, `email`, `password`)
VALUES (1, "created user", "new@gmail.com", "secret")
ON CONFLICT (id) DO UPDATE SET `name` = "updated user", `email` = EXCLUDED.`email`