SQLSTATE [23000]:完整性约束违规:1451无法删除或 更新父行:外键约束失败 (demopurpose_fundraising.campaign_product,CONSTRAINT campaign_product_campaign_id_foreign FOREIGN KEY(campaign_id) REFERENCES广告系列(ID))(SQL:从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');
});
campaign_id是campaign_product delete ..中的外键。
我想删除广告系列..
如何删除广告系列产品然后广告系列??
答案 0 :(得分:1)
除非您从campaign_id
表中删除campaign_product
,否则无法将其删除。在删除广告系列之前,从campaign_product
表中分离产品。例如:
$campaign = Campaign::query()->findOrFail($id); //find campaign
$campaign->products()->detach($campaign->product); //detach products from `campaign_products` table
$campaign->delete(); //delete the campaign
详细了解如何分离多对多关系记录:https://laravel.com/docs/5.6/eloquent-relationships#updating-many-to-many-relationships
答案 1 :(得分:0)
您所看到的是您无法删除模型,因为它仍然在您的数据库中有连接。您希望在删除相关模型之前创建一个首先删除所有关系的函数。
尝试将此添加到Campaign
模型。
protected static function boot() {
parent::boot();
static::deleting(function($campaign) { // before delete() method, call this
$campaign->products()->delete();
// do the rest of the cleanup...
});
}
如果您按照评论中链接中给出的流程进行操作,则可以防止此问题在将来发生。