2

I am trying to create a pivot table, with foreign keys, this is the migration I have made in Laravel:

public function up()
{
    Schema::create('player_position', function (Blueprint $table) {
        $table->integer('player_id')->unsigned()->index();
        $table->integer('position_id')->unsigned()->index();

        $table->foreign('player_id')->references('id')->on('players')->onDelete('cascade');
        $table->foreign('position_id')->references('id')->on('positions')->onDelete('cascade');
    });
}

But, I get an error:

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table player_position add constraint player_position_posi tion_id_foreign foreign key (position_id) references positions (id) on delete cascade)

                                                                         [PDOException]                                                        

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

I have read that usually foreign key constraint errors are about not assigning unsigned to fields, or already having records in the DB, but my DB is empty, and I my fields have unsigned, so don't know what is the problem?

Leff
  • 1,968
  • 24
  • 97
  • 201

2 Answers2

0

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

For a field to be defined as a foreign key, the referenced parent field must have an index defined on it. And the datatype of both the column and its size must be the same.

I think you are violating some of the above rule.

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
0

Remove ->index() method as it creates basic index while you want to add foreign key constraint which references primary key on another table.

 $table->integer('player_id')->unsigned();
 $table->integer('position_id')->unsigned();

 $table->foreign('player_id')->references('id')->on('players')->onDelete('cascade');
 $table->foreign('position_id')->references('id')->on('positions')->onDelete('cascade');
Amritpal Nagra
  • 650
  • 2
  • 6
  • 14