Laravel-违反完整性约束:1452



这是我的迁移:

public function up()
    {
      Schema::table('payments', function($table)
      {
        $table->dropColumn('invoice_id');
      });
    }
     public function down()
    {
      Schema::table('payments',function (Blueprint $table){
        $table->unsignedInteger('invoice_id')->index();
        $table->foreign('invoice_id')->references('id')->on('invoices')->onDelete('cascade');
      });
    }

当我运行php-artisanmigrate:rollback时,它会给我一个异常:

[IlluminateDatabaseQueryException]                                                                                                         
  SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`invoiceninja`.`#sq  
  l-418_46`, CONSTRAINT `payments_invoice_id_foreign` FOREIGN KEY (`invoice_id`) REFERENCES `invoices` (`id`) ON DELETE CASCADE) (SQL: alter   
  table `payments` add constraint `payments_invoice_id_foreign` foreign key (`invoice_id`) references `invoices` (`id`) on delete cascade)     

  [PDOException]                                                                                                                               
  SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`invoiceninja`.`#sq  
  l-418_46`, CONSTRAINT `payments_invoice_id_foreign` FOREIGN KEY (`invoice_id`) REFERENCES `invoices` (`id`) ON DELETE CASCADE)       

有人能帮我吗?

我不知道为什么在down()方法中有这个逻辑,因为通常它在up()中,但试着这样做:

public function down()
{
    Schema::table('payments', function (Blueprint $table){
        $table->unsignedInteger('invoice_id')->index();
    });
    Schema::table('payments', function (Blueprint $table){
        $table->foreign('invoice_id')->references('id')->on('invoices')->onDelete('cascade');
    });
}

我假设您正在运行down方法。第一行:

$table->unsignedInteger('invoice_id')->index();

加回列,我不知道Laravel,但我猜这会为列指定默认值0

$table->foreign('invoice_id')->references('id')->on('invoices')->onDelete('cascade');

如果引用的id列中没有0值,则会失败。

您可以通过允许invoice_id列为NULL并将其用作默认值来实现这一点。

我的第一站是检查新添加的列invoice_id中的值。

相关内容

  • 没有找到相关文章

最新更新