代码之家  ›  专栏  ›  技术社区  ›  Sagar Gautam

laravel中作为外键的可空列

  •  0
  • Sagar Gautam  · 技术社区  · 6 年前

    我在数据库中有客户表。客户与一个行业相关联。因为这个要求,, industry_id

    现在,当我想将此列添加为外键时,它显示以下错误。

    SQLSTATE[HY000]:一般错误:1215无法添加外键约束(SQL:alter table customers 添加约束 customers_industry_id_foreign 工业标识 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');
        }
    }
    

    是不是不可能实现我想要的?或者这是不合逻辑的? 如果我能够添加外键,那么我可以利用使用外键的各种优势。

    2 回复  |  直到 6 年前
        1
  •  0
  •   Sandeep Sudhakaran    6 年前

    推荐文章