[英]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.