2

这是我的迁移:

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 artisan migrate:rollback 它给了我这个异常:

[Illuminate\Database\QueryException]                                                                                                         
  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)       

谁能帮我 ?

4

2 回答 2

0

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

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

添加回列,我不知道 Laravel,但我猜这会为0列分配默认值。

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

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

您可以通过允许该invoice_idNULL并将其用作默认值来使其工作。

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

于 2016-04-19T10:44:26.677 回答
0

我不确定你为什么在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');
    });
}
于 2016-04-19T10:45:59.210 回答