简体   繁体   中英

Cannot add foreign key constraint in Laravel

I have an app where users belong to a team. Here is my test:

/** @test */
public function it_has_many_users()
{
    $team = factory(Team::class)->create();
    $users = factory(User::class, 3)->create([
        'team_id' => $team->getKey(),
    ]);

    $this->assertEquals(3, $team->users->count());
}

I have a foreign key setup on the users table like so:

Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('team_id')->nullable();

        $table->foreign('team_id')
            ->references('id')
            ->on('teams')
            ->onUpdate('cascade')
            ->onDelete('cascade');
    });

There is more to the migration, but for simplicity I have only included the necessary code. Here is my teams migration:

Schema::create('teams', function (Blueprint $table) {
    $table->bigIncrements('id');
});

When I run my test I get this error:

Illuminate\\Database\\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table users add constraint users_team_id_foreign foreign key ( team_id ) references teams ( id ) on delete cascade on update cascade)

I'm not sure what is wrong as I have other foreign keys set up the same way on other tables and they work fine. I do have all relationships set up correctly.

Set the team migration to earlier, before the user table migration happens. Otherwise, there is no teams table in existence yet to reference when creating the user table, and thus the error.

IE

Schema::create('teams', function (Blueprint $table) {...}

THEN

 Schema::create('users', function (Blueprint $table) {...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM