Laravel Невозможно обновить или удалить родительскую строку, ограничение внешнего ключа не выполнено - PullRequest
0 голосов
/ 27 декабря 2018

enter image description here я пытаюсь выполнить команду php artisan migrate: откат, и он выдает ошибку, что не может обновить или удалить родительскую строку. Не удается выполнить ограничение внешнего ключа.

возникла проблема.Когда я запускаю команду php artisan migrate, она успешно переносит все мои таблицы, но когда я запускаю команду отката, она выдает мне ошибку, ошибка происходит при моей миграции target_of_visits

    public function up()
{
    Schema::create('purpose_of_visits', function (Blueprint $table) {
        $table->increments('id');
        $table->string('purpose', 100);
        $table->string('description', 197);
        $table->integer('speciality_id')->unsigned()->nullable();
        $table->timestamp('created_at')->useCurrent();
        $table->timestamp('updated_at')->useCurrent();
        $table->softDeletes();
        $table->integer('created_by')->unsigned()->nullable();
        $table->integer('updated_by')->unsigned()->nullable();

        $table->foreign('speciality_id')->references('id')->on('specialities')->onDelete('cascade');
        $table->foreign('created_by')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('updated_by')->references('id')->on('users')->onDelete('cascade');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('purpose_of_visits');
}

и миграции моей специальности:

    public function up()
{
    Schema::create('specialities', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name', 50);
        $table->string('description',250)->nullable();
        $table->timestamp('created_at')->useCurrent();
        $table->timestamp('updated_at')->useCurrent();
        $table->softDeletes();
        $table->integer('created_by')->unsigned()->nullable();
        $table->integer('updated_by')->unsigned()->nullable();

        $table->foreign('created_by')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('updated_by')->references('id')->on('users')->onDelete('cascade');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('specialities');
}

Я не могу понять, в чем проблема, даже когда я использую onDelete ('каскад'), ваша помощь будет высоко оценена!

Ответы [ 3 ]

0 голосов
/ 27 декабря 2018

Снимите ограничения внешнего ключа таблицы перед ее удалением.

public function down()
{
    Schema::table('purpose_of_visits', function (Blueprint $table) {
        $table->dropForeign(['speciality_id']);
        $table->dropForeign(['created_by']);
        $table->dropForeign(['updated_by']);
    });
    Schema::dropIfExists('purpose_of_visits');
}
0 голосов
/ 27 декабря 2018

Извините за поздний ответ Есть две ситуации, когда эта ошибка может быть выдана

Например, у меня есть такие таблицы, как posts, authors

А вот моя таблица post Миграция

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->unsignedInteger('author_id');
            $table->foreign('author_id')->references('id')->on('authors')->onDelete('cascade');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

и вот моя authors миграция таблицы

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAuthorsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('authors', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('authors');
    }
}

Situation 1:

теперь, если миграция таблицы posts выполняется до миграции authors таблицы, это может привести к ошибке

Ситуация 2:

в некоторых случаях, если вы пропустите unsigned, может выдаться ошибка

Solution1:

, используйте

$table->unsignedInteger('speciality_id');
$table->unsignedInteger('speciality_id');
                $table->foreign('author_id')->references('id')->on('specialities')->onDelete('cascade');

вместо этого

$table->integer('speciality_id')->unsigned()->nullable();
$table->foreign('speciality_id')->references('id')->on('specialities')->onDelete('cascade');

, если это снова не удается, используйте это

try composer dumpautoload

adn, тогда Schema :: disableForeignKeyConstraints ();

В начале миграции

ив конце

Schema :: enableForeignKeyConstraints ();

например: ваша миграция может выглядеть как

public function up()
    {
    Schema::disableForeignKeyConstraints();
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();
        });

Schema::enableForeignKeyConstraints();
    }

и, если выдает ту же ошибку, пожалуйста, приложите ошибкуСнимок экрана и комментарий ниже

Надеюсь, это поможет

0 голосов
/ 27 декабря 2018

Убедитесь, что у вас есть speciality_id, create_by и updated_by в свойстве fillable вашей цели target_of_visits. См. Документы здесь .

Например, для вашей модели.

protected $fillable = ['speciality_id','created_by','updated_by'];
...