这是我的迁移:
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)
任何人都可以帮助我吗?
答案 0 :(得分:0)
我假设您正在运行down方法。第一行:
$table->unsignedInteger('invoice_id')->index();
添加回列,我不知道Laravel,但我猜这会为列分配一个默认值0
。
$table->foreign('invoice_id')->references('id')->on('invoices')->onDelete('cascade');
如果引用的0
列中没有id
值,则会失败。
您可以通过允许invoice_id
列为NULL
并将其用作默认值来实现此目的。
我的第一站是检查新重新添加的列invoice_id
中的值。
答案 1 :(得分: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');
});
}