这是我的迁移:
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
中的值。