staudenmeir/laravel-upsert

Laravel UPSERT 和 INSERT IGNORE 查询

v1.4 2020-08-19 21:00 UTC

This package is auto-updated.

Last update: 2024-09-14 22:21:09 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.9。

兼容性

安装

composer require staudenmeir/laravel-upsert:"^1.0"

用法

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 需要第二个参数,其中包含唯一标识记录的列(s)

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 \Staudenmeir\LaravelUpsert\Eloquent\HasUpsertQueries;
}

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

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

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

Lumen

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

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

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

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

贡献

请参阅 CONTRIBUTINGCODE OF CONDUCT 以获取详细信息。