terranc/eloquent-insert-on-duplicate-key

为 Eloquent 实现的 INSERT ON DUPLICATE KEY UPDATE 和 INSERT IGNORE 宏

1.0.3 2023-04-24 13:29 UTC

This package is not auto-updated.

Last update: 2024-09-23 20:06:07 UTC


README

此包已弃用,因为 Laravel 已添加了 upsertinsertOrIgnore

如果您需要 pivot 函数,它们非常容易实现

BelongsToMany::macro('attachUpsert', function ($id, array $attributes = []) {
    $this->newPivotStatement()->upsert($this->formatAttachRecords(
        $this->parseIds($id),
        $attributes
    ), null);
});

BelongsToMany::macro('attachOrIgnore', function ($id, array $attributes = []) {
    $this->newPivotStatement()->insertOrIgnore($this->formatAttachRecords(
        $this->parseIds($id),
        $attributes
    ));
});

此包提供宏,用于在 Laravel 的 ORM Eloquent 中对模型和 pivot 表执行 INSERT ... ON DUPLICATE KEY UPDATE 和 INSERT IGNORE 查询,使用 MySql 或 MariaDB。

安装

使用 composer 安装此包。

composer require guidocella/eloquent-insert-on-duplicate-key

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

InsertOnDuplicateKey\InsertOnDuplicateKeyServiceProvider::class,

用法

模型

从模型中调用 insertOnDuplicateKeyinsertIgnore,并传入要插入其表的数组数据。

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

User::insertOnDuplicateKey($data);

User::insertIgnore($data);

自定义 ON DUPLICATE KEY UPDATE 子句

只更新特定列

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

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

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

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

User::insertOnDuplicateKey([
    'id'    => 1,
    'name'  => 'created user',
], ['name' => 'updated user']);

生成的 SQL 是

INSERT INTO `users` (`id`, `name`) VALUES (1, "created user") ON DUPLICATE KEY UPDATE `name` = "updated user"

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

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

将生成

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

枢纽表

BelongsToMany 关系中调用 attachOnDuplicateKeyattachIgnore 以在枢纽表中执行插入。您可以通过 attach 接受的任何格式传递数据。

$pivotData = [
    1 => ['expires_at' => Carbon::today()],
    2 => ['expires_at' => Carbon::tomorrow()],
];

$user->roles()->attachOnDuplicateKey($pivotData);

$user->roles()->attachIgnore($pivotData);