【问题标题】:Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entryIlluminate\Database\QueryException 并带有消息“SQLSTATE [23000]:完整性约束违规:1062 重复条目
【发布时间】:2021-08-07 12:48:38
【问题描述】:

我正在学习 Scratch 的 Laravel-8 教程。现在我在本教程中https://laracasts.com/series/laravel-8-from-scratch/episodes/30[][1]。但是当我关注时,我有

Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'omnis' for key 'categories_name_unique' (SQL: insert into categories (name, slug, @987654326 @, created_at) 值 (omnis, vero-ipsam-atque-et-iusto-consequatur-inventore-quam-temporibus, 2021-08-06 05:40:33, 2021-08-06 05:40:33) )' 错误

在这里,我想创建 10 个 category_id 为 1 的帖子,所以我运行 php artisan tinker 和 App\Models\Post::factory(10)->create(['category_id'=> 1]);然后我有以下错误。

这是我的分类表

Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->string('slug')->unique();
            $table->timestamps();
        });

这是 CategoryFactory.php

public function definition()
    {
        return [
            'name' => $this -> faker -> word(),
            'slug' => $this -> faker -> slug()
        ];
    }

这是 PostFactory.php

public function definition()
    {
        return [
            'user_id' => User::factory(),
            'category_id' => Category::factory(),
            'title' => $this -> faker ->sentence(),
            'slug' => $this -> faker -> slug(),
            'excerpt' => $this -> faker -> sentence(),
            'body' => $this ->faker -> paragraph()
        ];
    }

这是 Post.php 模型

class Post extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function author()
    {
        return $this->belongsTo(User::class,'user_id');
    }
}

【问题讨论】:

  • 这个错误有什么不清楚的地方吗?您在应用程序的任何位置为列 category.name 插入重复值
  • 在我看来,您每次创建帖子时都尝试创建一个具有相同名称的新类别。名称被标记为唯一
  • 只创建 10 行时会出现重复,这很奇怪。但是您可以使用$this-> faker->unique()->word(), 来获取唯一值
  • Can Vural .... 我已经在我的 categoryFactory.php 中完成了这个,你可以看到这个但它不起作用。

标签: laravel laravel-8


【解决方案1】:

我在命令 App\Models\Post::factory(10)->create(['category_id' => 1]); 中找到了解决方案我错过了拼写 category_id。

【讨论】:

    【解决方案2】:

    为什么要保持此表的唯一性,如果您保持不变,那么您只能使用一次相同的名称。删除 unique(),这就是为什么当您尝试使用相同名称两次时会显示此错误,它不允许您仅插入一次可以插入的数据。

    $table->string('name')->unique();
    

    $table->string('name');
    

    【讨论】:

    • 问题不在于名称是唯一的,而是他尝试创建多个具有相同名称的类别而不是使用现有的类别ID,这将消除错误,但不会给出预期的结果。请在回答之前阅读完整的问题:“我想在这里创建 10 个 category_id 为 1 的帖子”
    猜你喜欢
    • 2016-05-23
    • 1970-01-01
    • 2016-01-16
    • 2014-09-16
    • 2018-06-06
    • 2020-12-20
    • 2016-03-10
    • 2015-03-31
    • 2019-09-12
    相关资源
    最近更新 更多