正确删除相关模型

Delete related model correctly

我的商店功能是

public function store(Request $request, Post $post)
{
    $comment = new Comment();
    $comment->fill($request->all());
    $post->comments()->save($comment);
}

我的销毁函数是

public function destroy(Post $post, Comment $comment)
{

}

我从文档中得到的存储函数 (Inserting & Updating Related Models)

那么通过 Post 模型删除评论的最佳做法是什么?

你可以尝试使用Laravel观察者这里是一个例子

要创建观察者,您可以

php artisan make:observer PostObserver

它将创建一个漂亮的样板文件。

class PostObserver
{

    public function deleting(Post $post){

        $comments =  $post->comments;
        $comments->delete();
    }

}

在你的 AppServiceProvider.php

Post::observe(PostObserver);

它会在您删除 Post 之前删除相关模型。

因为你们的关系是 hasManybelongsTo,你真的不需要删除评论 和 post。如果您遵守 Laravel 的命名约定,该评论作为自己的记录存在于它自己的 table 中,并通过 post_id 关联到 post。

在这种情况下,要删除评论,您只需简单地使用 delete 方法:

public function destroy(Post $post, Comment $comment)
{
    $comment->delete();
}

如果您在 Comment 模型上使用 SoftDeletes 特征,这将简单地将 deleted_at 设置为当前时间戳。如果没有,它将从数据库中删除记录。如果您正在使用 SoftDeletes 并想从 table 中删除记录(而不是仅仅设置 deleted_at),您可以使用 forceDelete(参见 Permanently删除模型):

public function destroy(Post $post, Comment $comment)
{
    $comment->forceDelete();
}

如果您只想销毁评论和 post 之间的引用,您可以在评论对象上使用 dissociate 方法。这实际上只是将 post_id 字段设置为 null 并且不会从 table.

中删除评论
public function destroy(Post $post, Comment $comment)
{
    $comment->post()->dissociate();
    $comment->save();
}

如果您真的想使用关系来确保只能删除属于给定 post 的评论,您可以这样做:

$post->comments()->whereKey($comment->id)->delete();

这将向查询添加一个额外的 where,确保评论的 post_id 等于 post 的 ID。

作为参考,如果您有多对多关系(belongsToMany 双向),您需要删除数据透视表 table 中的记录。为此,您可以使用 detach 或者您可以使用 sync 只提供应该保留的内容。