本文介绍了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.

错误

也许是我的模式吗?

帖子架构

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无法删除或更新父行:外键约束失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 05:06