无法删除或更新父行:即使存在onDelete级联和onUpdate级联,外键约束也会失败?

时间:2019-10-31 07:30:14

标签: laravel

违反完整性约束:1451无法删除或更新父行:外键约束失败

users Table
Schema::create('users', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->string('name');
  $table->string('email')->unique();
  $table->timestamp('email_verified_at')->nullable();
  $table->string('password');
  $table->rememberToken();
  $table->timestamps();
});
cv table

 Schema::create('cvs', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->unsignedBigInteger('user_id')->nullable();
  $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
  $table->string('name')->nullable();
  $table->string('contact')->nullable();
  $table->string('contact2')->nullable();
  $table->string('gender')->nullable();
  $table->string('email')->unique()->nullable();
  $table->string('paddress')->nullable();
});

2 个答案:

答案 0 :(得分:1)

原因可以是:

  • 您的CSV迁移先于Users。 看一下迁移名称(和日期)。应该是:

    2019_02_01_101010_create_users_table.php

    2019_02_02_101010_create_csv_table.php(外观,日期为2019_02_02)

然后开火php artisan:migrate

请确保在其他迁移中您有正确的日期。如果一个表想要与尚未创建的表建立关系,则迁移将无法进行。

祝你好运!

答案 1 :(得分:0)

在这种情况下,您需要先迁移users表,然后再迁移cvs 为此:

php artisan migrate --path=/database/migrations/selected

如果您已在需要迁移之前进行了迁移

php artisan migrate --path=/database/migrations/2014_10_12_000000_create_users_table.php

然后运行

php artisan migrate

它将自动为您迁移所有其余表

希望这会有所帮助