[英]Nullable column as foreign key in laravel
我在數據庫中有customer表。 客戶與行業相關聯。 由於要求,在創建客戶時, industry_id
為null。 稍后它將被更新並添加正確的行業ID。
現在,當我想將此列添加為外鍵時,它會顯示以下錯誤。
SQLSTATE [HY000]:一般錯誤:1215無法添加外鍵約束(SQL:alter table
customers
add constraintcustomers_industry_id_foreign
外鍵(industry_id
)引用industries
(id
))
我在客戶遷移中有以下代碼。
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCustomersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id')->comment="Customer Identifier";
$table->bigInteger('customer_category_id')->unsigned()->comment="Customer Category Identifier";
$table->bigInteger('industry_id')->unsigned()->nullable()->comment="Industry Identifier";
$table->string('email')->unique()->comment="Customer Email";
$table->timestamps();
$table->foreign('industry_id')->references('id')->on('industries');
$table->foreign('customer_category_id')->references('id')->on('customer_categories');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('customers');
}
}
這是行業遷移。
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateIndustriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('industries', function (Blueprint $table) {
$table->bigIncrements('id')->comment="Industry Indetifier";
$table->string('name')->comment="Industry Name";
$table->boolean('status')->default(true)->comment="Active or Inactive";
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('industries');
}
}
實現我想要的是不可能的? 或者它只是不合邏輯? 如果我能夠添加外鍵,那么我可以利用外鍵的各種優點。
將行業表中的id(primary_key)更改為唯一鍵,然后嘗試
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.