General error: 1005 when creating a key constraint - Laravel

我是研究僧i 提交于 2020-01-05 08:40:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!