删除父行数据时出现错误

时间:2018-03-20 06:26:55

标签: php mysql database sql-delete laravel-5.5

我想删除广告系列,但不删除广告系列,并发生以下错误。

  

SQLSTATE [23000]:完整性约束违规:1451无法删除或   更新父行:外键约束失败   (demopurpose_fundraisingcampaign_product,CONSTRAINT   campaign_product_campaign_id_foreign外键(campaign_id)   参考campaignid))(SQL:从campaign删除id   = 60)

广告系列表架构:

Schema::create('campaign', function (Blueprint $table) {
            $table->engine='InnoDB';
            $table->increments('id');
            $table->integer('users_id')->unsigned();
            $table->foreign('users_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
            $table->string('campaign_name');
            $table->float('campaign_goal',8,2);
            $table->string('discription',400);
            $table->string('image');
            $table->string('category');
            $table->date('start_date');
            $table->date('end_date');
            $table->float('total_fund',8,2);
});

campaign_product表架构:

Schema::create('campaign_product', function (Blueprint $table) {
            $table->engine='InnoDB';

            $table->increments('id');
            $table->integer('campaign_id')->unsigned();
            $table->foreign('campaign_id')->references('id')->on('campaign')->onDelete('cascade')->onUpdate('cascade');

            $table->integer('product_id')->unsigned();
            $table->foreign('product_id')->references('id')->on('product')->onDelete('cascade')->onUpdate('cascade');
        });

1 个答案:

答案 0 :(得分:1)

您应该更新迁移以执行删除操作。请参阅:https://laravel.com/docs/4.2/schema#foreign-keys

例如

(来自文档)

$table->foreign('user_id')
      ->references('id')->on('users')
      ->onDelete('cascade');

取决于您选择的数据库,可能还有其他选项,例如set null。

这里的问题是你设置了一个约束,但你很惊讶受到限制。设置onDelete行为,以便db为您执行处理。