【问题标题】:Cannot delete or update a parent row: a foreign key constraint fails even there is onDelete Cascade and onUpdate cascade?无法删除或更新父行:即使存在 onDelete Cascade 和 onUpdate 级联,外键约束也会失败?
【发布时间】:2019-10-31 16:16:25
【问题描述】:

完整性约束违规: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();
});

【问题讨论】:

    标签: laravel


    【解决方案1】:

    原因可能是:

    • 您的 CSV 迁移在用户之前。 看看迁移名称(和日期)。应该是:

      2019_02_01_101010_create_users_table.php

      2019_02_02_101010_create_csv_table.php(看,日期是2019_02_02)

    然后开火php artisan:migrate

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

    祝你好运!

    【讨论】:

      【解决方案2】:

      在这种情况下,您需要先迁移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
      

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

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 2017-06-11
        • 1970-01-01
        • 2019-05-25
        • 2014-11-11
        • 2018-05-12
        • 2017-09-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多