无法添加或更新 child 行:外键约束失败 - Laravel 7

Cannot add or update a child row: a foreign key constraint fails - Laravel 7

我正在尝试在我的访客和联系人

之间添加关系 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))

在 laravel 的最新版本中,主键是双整数。所以你可能需要改变这个

$table->整数('visitor_id')->无符号();

有了这个

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

访问者table中的id字段应该是bigIncrement

类型

如果您的 table 有数据,最好将已存在数据的列值设置为空,或将该列设置为可为空。

$table->bigInteger('visitor_id')->unsigned()->nullable();