【问题标题】:Nullable column as foreign key in laravel可空列作为laravel中的外键
【发布时间】:2019-11-07 06:59:57
【问题描述】:

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

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

SQLSTATE[HY000]:一般错误:1215 无法添加外键约束(SQL:更改表customers添加约束customers_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)改成唯一键,然后试试。
  • 你能显示industries的迁移吗?
  • @Jerodev 好的确定
  • 我添加了行业迁移。有什么问题吗 ?建议表示赞赏。
  • 尝试从industry_id中删除unsigned,使列的类型相同

标签: php mysql laravel migration


【解决方案1】:

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

【讨论】:

  • 我已经添加了问题
  • 请进入您的数据库并检查表结构,大多数行业表的id是主键自动生成的。请也从数据库中添加您的行业表结构。
猜你喜欢
  • 1970-01-01
  • 2021-12-02
  • 2018-07-08
  • 2015-08-26
  • 2014-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多