我在 Laravel 5.1 中使用数据库迁移和播种。
移民
public function up()
{
Schema::create('teachers', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('teacher_id')->unsigned();
$table->boolean('disable')->default(0);
$table->timestamps();
$table->unique(['user_id', 'teacher_id']);
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('teacher_id')->references('id')->on('users')->onDelete('cascade');
});
}
*** user_id 和teacher_id 必须是唯一的。
模型工厂
$factory->define(App\Teacher::class, function ($faker) {
return [
'user_id' => $faker->numberBetween(1, 59),
'teacher_id' => $faker->numberBetween(1, 59),
];
});
我在以下位置设置了播种机以产生 500 名教师关系DatabaseSeeder.php
:
factory(App\Teacher::class, 500)->create();
但我收到了这个错误:
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '10-11' for key 'teachers_user_id_teacher_id_
unique'
如您所见,***(唯一属性)导致了错误。有什么办法可以解决吗?你有什么想法?