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

Я пытаюсь добавить связь 1:1 между моим посетителем и контактом

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddRelationToVisitorsDRelationToVisitorsContacts extends Migration
{

    public function up()
    {


        Schema::table('contacts', function(Blueprint $table)
        {
            $table->bigInteger('visitor_id')->unsigned();
            $table->foreign('visitor_id')->references('id')->on('visitors')->onDelete('cascade');

        });

    }


    public function down()
    {

        Schema::table('contacts', function($table)
        {
            $table->dropForeign('contacts_visitor_id_foreign');
            $table->dropColumn('visitor_id');

        });

        Schema::table('visitors', function(Blueprint $table)
        {
            $table->dropColumn('contact_id');
        });

    }
}

При запуске

php artisan migrate
Migrating: 2020_04_16_104641_update_contacts_table_04_16_2020

Я продолжал получать

Illuminate\Database\QueryException 

  SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`bheng`.`#sql-e1_1f3`, CONSTRAINT `contacts_visitor_id_foreign` FOREIGN KEY (`visitor_id`) REFERENCES `visitors` (`id`) ON DELETE CASCADE) (SQL: alter table `contacts` add constraint `contacts_visitor_id_foreign` foreign key (`visitor_id`) references `visitors` (`id`) on delete cascade)

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:670
    666|         // If an exception occurs when attempting to run a query, we'll format the error
    667|         // message to include the bindings with SQL, which will make this exception a
    668|         // lot more helpful to the developer instead of just the database's errors.
    669|         catch (Exception $e) {
  > 670|             throw new QueryException(
    671|                 $query, $this->prepareBindings($bindings), $e
    672|             );
    673|         }
    674| 

      +11 vendor frames 
  12  database/migrations/2020_04_16_104641_update_contacts_table_04_16_2020.php:31
      Illuminate\Support\Facades\Facade::__callStatic("table")

      +22 vendor frames 
  35  artisan:37
      Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

enter image description here

Ответы [ 2 ]

1 голос
/ 16 апреля 2020

Поле id в таблице посетителей должно иметь тип bigIncrement

1 голос
/ 16 апреля 2020

В последних версиях laravel первичным ключом является biginteger. поэтому вам, возможно, придется изменить это

$ table-> integer ('visitor_id') -> unsigned ();

с помощью этого

$ table-> bigInteger (' visitor_id ') -> без знака ();

...