gpt4 book ai didi

php - Laravel 中可空列作为外键

转载 作者:行者123 更新时间:2023-11-29 15:51:22 25 4
gpt4 key购买 nike

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

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

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))

我在客户迁移中有以下代码。

<?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) 更改为唯一键,然后尝试

关于php - Laravel 中可空列作为外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56754037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com