0

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.

2
  • Silly question, but is teams earlier in the migration than users? IE is teams actually a table when users is run? Commented Jul 2, 2019 at 16:38
  • teams migration is after Commented Jul 2, 2019 at 16:41

1 Answer 1

2

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) {...}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.