guidocella / eloquent-insert-on-duplicate-key
v2.2.5
2020-09-10 10:13 UTC
Requires
- php: >=5.6.4
- illuminate/database: ^5.4||^6||^7||^8
Requires (Dev)
- laravel/laravel: ^8
- phpunit/phpunit: ^9
README
由于 Laravel 已添加了 upsert
和 insertOrIgnore
,因此此包已被弃用。
如果需要分叉函数,它们很容易实现
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 中对模型和分表执行 INSERT ... ON DUPLICATE KEY UPDATE 和 INSERT IGNORE 查询(使用 MySql 或 MariaDB)。
安装
使用 composer 安装此包。
composer require guidocella/eloquent-insert-on-duplicate-key
如果您尚未使用包自动发现,请将服务提供者添加到 config/app.php
中的包服务提供者中。
InsertOnDuplicateKey\InsertOnDuplicateKeyServiceProvider::class,
使用方法
模型
从一个模型中调用 insertOnDuplicateKey
或 insertIgnore
,并传入其表中要插入的数据数组。
$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 的用户不存在,则将创建一个名为 'created user' 的用户。如果它已存在,则将更新为 '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
关系中调用 attachOnDuplicateKey
和 attachIgnore
来在其分表上运行插入操作。您可以传递 attach
接受的任何格式的数据。
$pivotData = [ 1 => ['expires_at' => Carbon::today()], 2 => ['expires_at' => Carbon::tomorrow()], ]; $user->roles()->attachOnDuplicateKey($pivotData); $user->roles()->attachIgnore($pivotData);