1062 重复条目 'General' - 如果已有同名类别,则跳过插入

1062 Duplicate entry 'General' - skip the insert if there is already a category with same name

我有一个这样的迁移 post_categories:

 public function up()
    {
        Schema::create('post_categories', function (Blueprint $table) {
            $table->id();
            
            $table->foreignId('post_id')
            ->nullable()
            ->constrained('posts');

            $table->unsignedSmallInteger('category_id')->nullable();
            $table->string('category_name')->nullable();
}    

并且在 Laravel nova 资源的 fields 方法中有一些代码存储在上面 table 从 API 请求返回的一些类别:

public function fields(Request $request)
    {
        $postInformation = (new postInformation)->handle(['field' => 'slug', 'value' => $this->slug]);
        $postId =  $postInformation['id'];

        try{
            DB::table('post_categories')->insert(
                array_map(fn ($category) => [
                    'post_id' => $postId,
                    'category_id' => $category['id'],
                    'category_name' => $category['name']['en_gb'],
                ], $postInformation['categories']['data'])
            );
        } 
        
}

它有效,但我收到此错误:

exception: "Illuminate\Database\QueryException"
file: "/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php"
line: 742
message: "SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'General'

如果 table 中已经存储了类别名称,您知道如何跳过该插入,以避免此类错误吗?

有许多方法可以使用 Query Builder

完成您想要的

insertOrIgnore

这是此方法的一个示例:

$data = array_map(fn ($category) => [
    'post_id' => $postId,
    'category_id' => $category['id'],
    'category_name' => $category['name']['en_gb'],
], $postInformation['categories']['data']);

DB::table('post_categories')->insertOrIgnore($data);

upsert

这是此方法的一个示例:

$data = array_map(fn ($category) => [
    'post_id' => $postId,
    'category_id' => $category['id'],
    'category_name' => $category['name']['en_gb'],
], $postInformation['categories']['data']);

DB::table('post_categories')->upsert($data, ['the_column_must_be_unique'], ['the_columns_you_want_update_here']);

updateOrInsert

这是此方法的一个示例:

$data = array_map(fn ($category) => [
    'post_id' => $postId,
    'category_id' => $category['id'],
    'category_name' => $category['name']['en_gb'],
], $postInformation['categories']['data']);

DB::table('post_categories')->updateOrInsert($data, ['the_columns_you_want_update_here' => $postId]);

还有很多方法可以使用 Eloquent 完成您想要的,您会在 section

中找到许多示例