问题
When trying to add a foreign key constraint in Laravel I am getting the following error.
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table 'ts.#sql-5769_62' (errno: 150)
I have 2 tables, users
and teams
. The relationship is teams can have many users and users have one team.
Users
$table->increments('id');
$table->integer('team_id');
$table->string('name', 255);
$table->string('username', 32)->unique();
$table->string('email', 320);
$table->string('password', 64);
$table->foreign('team_id')->references('id')->on('teams');
$table->timestamps();
Teams
$table->increments('id');
$table->string('team_name', 255);
$table->string('website', 255);
$table->timestamps();
What am I doing wrong? Also this is my first time using migrations so any help in pointing out silly errors is welcomed.
回答1:
Try to specify unsigned
for team_id
:
$table->integer('team_id')->unsigned();
You primary key $table->increments('id');
is an unsigned integer, so the foreign key $table->integer('team_id');
should match it's type.
Quoted from Laravel docs:
Note: When creating a foreign key that references an incrementing integer, remember to always make the foreign key column unsigned.
Update
Also make sure you create the team
table first, so the Schema builder don't attempt to create a foreign key on a non existing table.
来源:https://stackoverflow.com/questions/20532430/general-error-1005-when-creating-a-key-constraint-laravel