簡體   English   中英

無法在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());
}

我在用戶表上有一個外鍵設置,如下所示:

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 )在更新級聯上的刪除級聯上引用teamsid ))

我不確定是什么問題,因為我在其他表上也以相同的方式設置了其他外鍵,並且它們工作正常。 我確實正確設置了所有關系。

在用戶表遷移發生之前,將團隊遷移設置為更早。 否則,在創建用戶表時就沒有引用的team表,因此會出現錯誤。

IE瀏覽器

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

然后

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM