Laravel无法删除或更新父行:外键约束失败 [英] Laravel Cannot delete or update a parent row: a foreign key constraint fails

查看:80
本文介绍了Laravel无法删除或更新父行:外键约束失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,用户无法删除某条喜欢的帖子,但以前一直在工作,但是当我将链接与喜欢链接时,出现此错误,除非我删除,否则我什至无法在Sequel Pro中将其删除与该帖子相关的点赞.

For some reason a user cannot delete a post if it has been liked, it was working before but when I linked posts with likes I have been getting this error, I can't even delete it in Sequel Pro, unless I delete the likes associated with the post first.

错误

SQLSTATE [23000]:违反完整性约束:1451无法删除或 更新父行:外键约束失败 (eliapi8.likes,CONSTRAINT likes_post_id_foreign外键 (post_id)参考posts(id))(SQL:从posts删除,其中 id = 149)

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (eliapi8.likes, CONSTRAINT likes_post_id_foreign FOREIGN KEY (post_id) REFERENCES posts (id)) (SQL: delete from posts where id = 149)

也许是我的模式吗?

帖子架构

Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->text('body');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users');
    $table->timestamps();
});

喜欢模式

Schema::create('likes', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('post_id')->unsigned();
    $table->integer('user_id')->unsigned();
    $table->foreign('post_id')->references('id')->on('posts');
    $table->foreign('user_id')->references('id')->on('users');
    $table->softDeletes();
    $table->timestamps();
});

我可以喜欢和不喜欢帖子,但是用户无法删除喜欢的帖子.

I can like and unlike a post, but a user cannot delete a post that has been liked.

PostController.php

public function destroy(Post $post){

    $this->authorize('delete', $post);
    $postl =  Post::with('likes')->whereId($post)->delete();

    if ($post->delete()) {
        if($postl){
             return response()->json(['message' => 'deleted']);
        }  
    };

    return response()->json(['error' => 'something went wrong'], 400);
}

推荐答案

是的,这是您的架构. likes.post_id上的约束将阻止您从posts表中删除记录.

Yes, it's your schema. The constraint on likes.post_id will prevent you from deleting records from the posts table.

一种解决方案可能是在likes迁移文件中使用onDelete('cascade'):

One solution could be using onDelete('cascade') in the likes migration file:

Schema::create('likes', function (Blueprint $table) {
    // Some other fields...

    $table->integer('post_id')->unsigned();
    $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
});

这样,当帖子被删除时,所有相关的点赞也将被删除.

This way, when a post is deleted, all related likes will be deleted too.

或者,如果您有从Post模型到Like模型的关系,则可以在删除帖子本身之前$post->likes()->delete().

Or, if you have a relationship from the Post model to the Like model, you can $post->likes()->delete() before deleting the post itself.

这篇关于Laravel无法删除或更新父行:外键约束失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆