Laravel添加外键并获取无法添加或更新子行错误

问题描述 投票:0回答:1

对于这个迁移文件作为payments表我想在其他迁移文件中添加其他列设置外键,在终端运行命令后我得到此错误:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`laravel`.`#sql-1f1_42b`, CONSTRAINT `payments_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DE
  LETE CASCADE) (SQL: alter table `payments` add constraint `payments_product_id_foreign` foreign key (`product_id`) references `
  products` (`id`) on delete cascade)

我的payments迁移文件:

public function up()
{
    Schema::create('payments', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->string('resnumber');
        $table->string('price');
        $table->boolean('payment')->default(false);
        $table->timestamps();
    });
}

我想用这个文件添加product_id列:

class SetProductIdForeignToPayment extends Migration
{
    public function up()
    {
        Schema::table('payments', function (Blueprint $table) {
            $table->integer('product_id')->unsigned()->index()->default(0);
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        });

    }
    public function down()
    {

    }
}

我该如何解决这个问题?

laravel laravel-5
1个回答
1
投票

->default(0)改为->nullable()

© www.soinside.com 2019 - 2024. All rights reserved.