无法在 Laravel 中添加外键约束
Cannot add foreign key constraint in Laravel
我有一个用户属于一个团队的应用程序。这是我的测试:
/** @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());
}
我在用户 table 上设置了外键,如下所示:
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');
});
迁移还有更多内容,但为简单起见,我只包含了必要的代码。这是我的 teams
迁移:
Schema::create('teams', function (Blueprint $table) {
$table->bigIncrements('id');
});
当我 运行 我的测试我得到这个错误:
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)
我不确定哪里出了问题,因为我在其他 table 上以相同的方式设置了其他外键,而且它们工作正常。我确实正确设置了所有关系。
将团队迁移设置为更早,在用户 table 迁移发生之前。否则,在创建用户 table 时,尚无团队 table 可供参考,因此会出现错误。
IE
Schema::create('teams', function (Blueprint $table) {...}
然后
Schema::create('users', function (Blueprint $table) {...}
我有一个用户属于一个团队的应用程序。这是我的测试:
/** @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());
}
我在用户 table 上设置了外键,如下所示:
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');
});
迁移还有更多内容,但为简单起见,我只包含了必要的代码。这是我的 teams
迁移:
Schema::create('teams', function (Blueprint $table) {
$table->bigIncrements('id');
});
当我 运行 我的测试我得到这个错误:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
users
add constraintusers_team_id_foreign
foreign key (team_id
) referencesteams
(id
) on delete cascade on update cascade)
我不确定哪里出了问题,因为我在其他 table 上以相同的方式设置了其他外键,而且它们工作正常。我确实正确设置了所有关系。
将团队迁移设置为更早,在用户 table 迁移发生之前。否则,在创建用户 table 时,尚无团队 table 可供参考,因此会出现错误。
IE
Schema::create('teams', function (Blueprint $table) {...}
然后
Schema::create('users', function (Blueprint $table) {...}