У меня есть таблица клиентов в базе данных. Клиент связан с отраслью. Из-за требования industry_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');
}
}
Разве невозможно достичь того, чего я хочу? или это просто нелогично?
Если я могу добавить внешний ключ, я могу использовать различные преимущества использования внешнего ключа.