【发布时间】: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 中完成了这个,你可以看到这个但它不起作用。