Laravel 5.6 set миграции обнуляемый внешний идентификатор - PullRequest
0 голосов
/ 29 января 2019

Это всплывающее окно с ошибкой:

#1452 - Cannot add or update a child row: a foreign key constraint fails (`ltfrbr10infosystem`.`franchises`, CONSTRAINT `franchises_operator_id_foreign` FOREIGN KEY (`operator_id`) REFERENCES `operators` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)

Миграция Laravel:

public function up()
{
    Schema::create('franchises', function (Blueprint $table) {
        $table->increments('id');

        $table->integer('operator_id')->nullable()->unsigned();
        $table->foreign('operator_id')->references('id')->on('operators')->onDelete('cascade')->onUpdate('cascade');

        $table->string('case_number')->nullable();
        $table->string('business_address')->nullable();
        $table->date('date_granted')->nullable();
        $table->date('expiry_date')->nullable();
        $table->string('route_name')->nullable();
        $table->string('deno')->nullable();
        $table->integer('authorize_units')->nullable();
        $table->string('remarks')->nullable();
        $table->timestamps();
    });
}

Я пробовал это, но все равно это дает мне ошибку

$table->integer('operator_id')->nullable()->unsigned()->change();

Я также пробовал это

$table->integer('operator_id')->unsigned()->default(null);

Как сделать внешний ключ operator_id по умолчанию пустым?

Ответы [ 3 ]

0 голосов
/ 29 января 2019

Я думаю, вы получите эту ошибку, потому что запись, которую вы пытаетесь вставить, содержит неправильное значение для столбца operator_id.Это значение не является правильным идентификатором оператора и не равно нулю (это может быть 0, «ноль» или пустая строка, ...)

Можете ли вы вставить здесь точный запрос SQL, который вызывает эту ошибку?

0 голосов
/ 29 января 2019

Добавьте эту функцию внутрь и запустите php artisan migrate: refresh --seed

public function up(){

    Schema::disableForeignKeyConstraints();
    Schema::create('franchises', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('operator_id')->unsigned()->nullable();
    $table->foreign('operator_id')->references('id')->on('operators')->onDelete('cascade')->onUpdate('cascade');
    $table->string('case_number')->nullable();
    $table->string('business_address')->nullable();
    $table->date('date_granted')->nullable();
    $table->date('expiry_date')->nullable();
    $table->string('route_name')->nullable();
    $table->string('deno')->nullable();
    $table->integer('authorize_units')->nullable();
    $table->string('remarks')->nullable();
    $table->timestamps();
});Schema::enableForeignKeyConstraints();}
0 голосов
/ 29 января 2019

Если данные в вашей базе данных не важны, вы можете обновить свои миграции и базу данных, используя

php artisan migrate: refresh

Это откатит и перенесет всеваши миграции снова.Убедитесь, что вы написали правильный метод down, также миграция должна выглядеть следующим образом:

public function up()
{
    Schema::create('franchises', function (Blueprint $table) {
        $table->increments('id');

        $table->unsignedInteger('operator_id')->nullable();
        $table->foreign('operator_id')->references('id')->on('operators')->onDelete('cascade')->onUpdate('cascade');

        $table->string('case_number')->nullable();
        $table->string('business_address')->nullable();
        $table->date('date_granted')->nullable();
        $table->date('expiry_date')->nullable();
        $table->string('route_name')->nullable();
        $table->string('deno')->nullable();
        $table->integer('authorize_units')->nullable();
        $table->string('remarks')->nullable();
        $table->timestamps();
    });
}

Другой способ сделать это - создать новую миграцию, подобную этой:

public function up()
{
    Schema::table('franchises', function (Blueprint $table) {

        $table->unsignedInteger('operator_id')->nullable()->change();


    });
}
...