jeudi 29 octobre 2015

Laravel seeding - unique pairs of user and teacher IDs

I am using database migration and seeding in Laravel 5.1.

Migration

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 and teacher_id must be unique together.

Model Factory

$factory->define(App\Teacher::class, function ($faker) {
    return [
        'user_id'           => $faker->numberBetween(1, 59),
        'teacher_id'        => $faker->numberBetween(1, 59),
    ];
});

I set up the seeder for producing 500 teacher relational in DatabaseSeeder.php: factory(App\Teacher::class, 500)->create();

but i got this error:

[PDOException] 
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '10-11' for key 'teachers_user_id_teacher_id_ 
unique'

As you can see, the *** (unique property) caused the error. is there any way to fix it? What is your idea?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire