【问题标题】:Cannot add foreign key constraint in Laravel无法在 Laravel 中添加外键约束
【发布时间】:2019-11-13 08:07:56
【问题描述】:

我有一个用户属于一个团队的应用。这是我的测试:

/** @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());
}

我在用户表上设置了一个外键,如下所示:

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]:一般错误:1215 无法添加外键约束(SQL:alter table users 添加约束users_team_id_foreign 外键(team_id)引用teams(@987654329 @) on delete cascade on update cascade)

我不确定出了什么问题,因为我在其他表上以相同的方式设置了其他外键并且它们工作正常。我确实正确设置了所有关系。

【问题讨论】:

  • 愚蠢的问题,但是团队迁移的时间比用户早吗?运行用户时IE实际上是一个表?
  • 团队迁移之后

标签: php mysql database laravel database-migration


【解决方案1】:

在用户表迁移发生之前将团队迁移设置为更早。否则,在创建用户表时,不存在可引用的团队表,从而导致错误。

浏览器

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

那么

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

【讨论】:

    猜你喜欢
    • 2020-09-12
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2018-11-25
    • 2016-11-11
    • 2017-09-06
    • 2017-03-03
    相关资源
    最近更新 更多