You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel应用中如何仅显示已审核的评论回复?

解决评论回复仅显示已审核内容的问题

当前父评论已经通过approved = 1的条件过滤,但评论回复直接调用$comment->replies关联时未添加审核状态约束,导致未审核的回复也会被展示。以下是几种可行的解决方法:

方法一:在模型关联中添加全局审核约束(推荐)

打开Comment模型,找到定义replies关联的方法,添加where('approved', 1)的条件,这样每次调用$comment->replies都会自动过滤已审核的回复:

public function replies()
{
    return $this->hasMany(Comment::class, 'parent_id')
        ->where('approved', 1)
        ->orderBy('id', 'asc'); // 可根据需求调整排序规则
}

方法二:预加载时过滤回复(优化查询性能)

修改控制器中的get_commentQuery方法,使用with预加载回复并添加审核条件,同时避免N+1查询问题:

private function get_commentQuery( int $article_id, int $limit = 0, int $offset = 0 ): object
{
    $commentQuery = Comment::where( [ 'article_id' => $article_id, 'approved' => 1 ] )
        // 预加载已审核的回复
        ->with(['replies' => function ($query) {
            $query->where('approved', 1)
                ->orderBy('id', $this->comments_orderby_direction);
        }])
        ->orderBy( 'id', $this->comments_orderby_direction );

    if ( $offset > 0 ) {
        $commentQuery = $commentQuery->offset( $offset );
    }
    if ( $limit > 0 ) {
        $commentQuery = $commentQuery->limit( $limit );
    }

    return $commentQuery;
}

方法三:模板中临时过滤(不推荐)

如果暂时无法修改模型或控制器,可在blade模板中循环回复时添加条件判断,但此方法会先加载所有回复再内存过滤,性能较差:

@if (count($comment->replies->where('approved', 1)))
    <ul class="children">
        @foreach ($comment->replies->where('approved', 1) as $reply)
            <!-- 回复内容渲染 -->
        @endforeach
    </ul>
@endif

内容的提问来源于stack exchange,提问作者Razvan Zamfir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 10:54:55