且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel无法删除或更新父行:外键约束失败

更新时间:2023-12-05 16:01:58

是的,这是您的架构. 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.