简体   繁体   English

无法在Laravel中添加外键约束

[英]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: 这是我的teams迁移:

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) Illuminate \\ Database \\ QueryException:SQLSTATE [HY000]:常规错误:1215无法添加外键约束(SQL:alter table users添加约束users_team_id_foreign外键( team_id )在更新级联上的删除级联上引用teamsid ))

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. 否则,在创建用户表时就没有引用的team表,因此会出现错误。

IE IE浏览器

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

THEN 然后

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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