簡體   English   中英

在這種情況下是否可以具有可為空的外鍵?

[英]Is it possible to have a nullable foreign key in this scenario?

我正在嘗試使用競賽表的外鍵創建“ teams”表,但是如何將外鍵設置為nullable?

Schema::create('teams', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name')->unique();
    $table->string('place');
    $table->string('competition')->nullable()->default(null);
    $table->foreign('competition')->references('name')->on('competitions')->onDelete('set null');
    $table->timestamps();
});

Schema::create('competitions', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name')->unique();
    $table->timestamps();
});

FK可以為空是可以接受的,這只是意味着您的團隊還不屬於比賽,因此我認為您有正確的主意。 我猜,因為你嘗試將涉及您收到一個錯誤teams表來competitions的前桌competitions已經創建的表。

首先創建competitions表。 如果已創建teams表,則可能需要先刪除它,然后嘗試再次運行遷移。

也可能是與name列相關的問題。 理想情況下,你應該命名該列competition_id而不是competition和與它的id在你的專欄competitions表。 name列放在像您這樣的比賽中是唯一的應該具有預期的效果,但是查詢可能會變慢,因為它會在varchar上創建較大的索引。

如果在“ name列上執行此操作,則在需要更新比賽名稱時可能會遇到更多問題。 如果您與ID有關,那么這永遠不會成為問題,因為您通常不會更改ID。 我認為您仍然可以通過這種方式工作,您只需要向FK添加onUpdate('cascade')

您只需要先創建competitions表,然后再創建teams表即可。

嘗試這樣:

Schema::create('competitions', function (Blueprint $table) {
      $table->increments('id');
      $table->string('name')->unique();
     $table->timestamps();
});    

Schema::create('teams', function (Blueprint $table) {
      $table->increments('id');
      $table->string('name')->unique();
      $table->string('place');
      $table->string('competition')->nullable()->default(null);
      $table->timestamps();
 });

Schema::table('teams', function (Blueprint $table) {
     $table->foreign('competition')->references('name')
      ->on('competitions')->onDelete('set null');
 });

暫無
暫無

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

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