iamirnet/laravel-upsert

Laravel UPSERT 和 INSERT IGNORE 查询,支持升级 Laravel 8x,9x,10x,11x

dev-master 2024-05-24 06:39 UTC

This package is auto-updated.

Last update: 2024-09-24 07:22:13 UTC


README

Code Coverage Scrutinizer Code Quality Latest Stable Version Total Downloads License

重要

该包的代码已合并到 Laravel 8.10+,并且现在原生支持 UPSERT 查询。

简介

这个 Laravel 扩展为查询构建器和 Eloquent 添加了对 INSERT & UPDATE(UPSERT)和 INSERT IGNORE 的支持。

支持 Laravel 5.5、8.x、9.x、10.x、11x。

兼容性

安装

composer require iamirnet/laravel-upsert

用法

INSERT & UPDATE (UPSERT)

考虑这个具有唯一 username 列的 users

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('username')->unique();
    $table->boolean('active');
    $table->timestamps();
});

使用 upsert() 插入新用户或更新现有用户。在此示例中,一个不活跃的用户将被重新激活,并且将更新 updated_at 时间戳。

DB::table('users')->upsert(
    ['username' => 'foo', 'active' => true, 'created_at' => now(), 'updated_at' => now()],
    'username',
    ['active', 'updated_at']
);

将第一个参数作为要插入的值提供。这可以是一个记录或多个记录。

第二个参数是唯一标识记录的列(s)。除了 SQL Server 之外的所有数据库都需要这些列具有 PRIMARYUNIQUE 索引。

将第三个参数作为要更新的列提供(可选)。默认情况下,将更新所有列。您可以提供列名和文字或原始表达式(见下文)中的键值对。

以下是一个复合键和原始表达式的示例

Schema::create('stats', function (Blueprint $table) {
    $table->unsignedInteger('post_id');
    $table->date('date');
    $table->unsignedInteger('views');
    $table->primary(['post_id', 'date']);
});

使用 upsert() 记录访问。查询将为每个帖子和日期创建一个新记录或增加现有视图计数器。

DB::table('stats')->upsert(
    [
        ['post_id' => 1, 'date' => now()->toDateString(), 'views' => 1],
        ['post_id' => 2, 'date' => now()->toDateString(), 'views' => 1],
    ],
    ['post_id', 'date'],
    ['views' => DB::raw('stats.views + 1')]
);

INSERT IGNORE

您还可以在忽略重复键错误的情况下插入记录。

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('username')->unique();
    $table->timestamps();
});

DB::table('users')->insertIgnore([
    ['username' => 'foo', 'created_at' => now(), 'updated_at' => now()],
    ['username' => 'bar', 'created_at' => now(), 'updated_at' => now()],
]);

SQL Server 需要第二个参数,其中包含唯一标识记录的列。

DB::table('users')->insertIgnore(
    ['username' => 'foo', 'created_at' => now(), 'updated_at' => now()],
    'username'
);

Eloquent

您可以使用 UPSERT 和 INSERT IGNORE 查询与 Eloquent 模型一起使用。

在 Laravel 5.5–5.7 中,这需要 HasUpsertQueries 特性。

class User extends Model
{
    use \iamirnet\LaravelUpsert\Eloquent\HasUpsertQueries;
}

User::upsert(['username' => 'foo', 'active' => true], 'username', ['active']);

User::insertIgnore(['username' => 'foo']);

如果模型使用时间戳,则 upsert()insertIgnore() 将自动将时间戳添加到插入值中。此外,upsert() 还会将 updated_at 添加到更新的列。

Lumen

如果使用 Lumen,则必须手动实例化查询构建器。

$builder = new \iamirnet\LaravelUpsert\Query\Builder(app('db')->connection());

$builder->from(...)->upsert(...);

在 Eloquent 中,对于 Lumen 的所有版本,都需要 HasUpsertQueries 特性。

贡献

有关详细信息,请参阅CONTRIBUTINGCODE OF CONDUCT