Laravel Cannot delete or update a parent row: a foreign key constraint fails

后端 未结 1 440
别那么骄傲
别那么骄傲 2020-12-06 05:23

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 dele

相关标签:
1条回答
  • 2020-12-06 06:07

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

    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.

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

    0 讨论(0)
提交回复
热议问题