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
usersadd constraintusers_team_id_foreignforeign key (team_id) referencesteams(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.