可空列作为Laravel中的外键

时间:2019-06-25 12:26:17

标签: php mysql laravel migration

我在数据库中有客户表。客户与行业相关联。由于有此要求,创建客户时customers为空。稍后将对其进行更新,并添加正确的行业ID。

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

  

SQLSTATE [HY000]:常规错误:1215无法添加外键约束(SQL:更改表customers_industry_id_foreign添加约束industry_id外键(industries)引用id < br />      (<?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');
    }
}

这里是产业迁移。

dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True; 
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells; 

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

1 个答案:

答案 0 :(得分:0)

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