简体   繁体   中英

Nullable column as foreign key in laravel

I have customers table in the database. A customer is associated with an industry. Because of the requirement, industry_id is null when customer is created. later it will be updated and correct industry id is added.

Now, when I want to add this column as foreign key it shows following error.

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table customers add constraint customers_industry_id_foreign foreign key ( industry_id ) references industries
( id ))

I have following code in customers migration.

<?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');
    }
}

Here is industries migration.

<?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');
    }
}

Is it impossible to achieve what I want ? or it is just illogical ? If I am able to add foreign key then I can take various advantages of using foreign key.

将行业表中的id(primary_key)更改为唯一键,然后尝试

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM