我正在尝试使用比赛表的外键创建“teams”表,但如何将外键设置为可为空?
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 可以为空是可以接受的,这只是意味着您的团队还不属于比赛,所以我认为您的想法是正确的。我猜您遇到了错误,因为您试图在创建 competitions
表之前将 teams
表与 competitions
表相关联。
首先创建competitions
表。如果创建了 teams
表,您可能需要先删除它,然后再次尝试运行迁移。
它也可能是与 name
列相关的问题。理想情况下,您应该将该列命名为 competition_id
而不是 competition
并将其关联到 competitions
中的 id
列 table 。让 name
列在比赛中像您一样独一无二应该会产生预期的效果,但查询可能会变慢,因为它会创建一个更大的索引,将它放在 varchar 上。
如果您在 name
列上执行此操作,那么如果您需要更新比赛名称,您可能会遇到更多问题。如果您与 id 相关,这永远不会成为问题,因为您通常不会更改 id。我认为你的仍然可以这样工作,你只需要添加一个 onUpdate('cascade')
以及你的 FK。
关于php - 在这种情况下是否可以有一个可为空的外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44335247/