Foreign key constraint error when adding through m

2019-09-07 02:47发布

I am trying to create a foreign key constraint between my two tables on Laravel 4, User and GP. A user can be associated with many GPs. The foreign key is 'Practice_ID' in the users table, which associates with the ID in the GP table.

    public function up()
{

    // Creates GP table
    Schema::create('gp', function($ta)
    {
        $ta->bigIncrements('id');
        $ta->string('address_1');
        $ta->string('address_2');
        $ta->string('address_3');
        $ta->string('post_code');
        $ta->timestamps();
    });

    // Creates the users table
    Schema::create('users', function($table)
    {
        $table->increments('id');
        $table->string('username');
        $table->string('email');
        $table->string('password');
        $table->string('confirmation_code');
        $table->boolean('confirmed')->default(false);
        $table->bigInteger('practice_id');
        $table->foreign('practice_id')->references('id')->on('gp');
        $table->timestamps();
    });

    // Creates password reminders table
    Schema::create('password_reminders', function($t)
    {
        $t->string('email');
        $t->string('token');
        $t->timestamp('created_at');
    });

}

The error I am getting is:

[Exception]
SQLSTATE[HY000]: General error: 1005 Can't create table 'doctor.#sql-3ac_a4' (errno: 150) (SQL: alter table users add constraint users_practice_id_foreign foreign key (practice_id) references gp (id)) (Bindings: array (
))

1条回答
叛逆
2楼-- · 2019-09-07 02:49

err 150 is most likely a data type mismatch.

delcare the foregin key as an unsigned int in the users table:

$table->integer('practice_id')->unsigned();

Also verify your db engine is INNODB that supports FK constraints

查看更多
登录 后发表回答