使用 Laravel eloquent 统计所有嵌套关系记录

问题描述 投票:0回答:1

目前,我正在为一篇模型如下的帖子建立评论:

class Comment extends Model
{
    use HasFactory;

    protected $fillable = ['user_id', 'post_id', 'parent_comment_id', 'text', 'is_approved', 'upvotes', 'downvotes'];

    protected $with = ['post'];

    public function post()
    {
        return $this->belongsTo(Post::class, 'post_id');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function replies()
    {
        return $this->hasMany(Comment::class, 'parent_comment_id');
    }
}

并且很快数据库是:

id parent_comment_id 文字
1 文字1
2 1 文字2
3 2 文字3
4 3 文字4
5 4 文字5

例如:如果选择Comment ID(1),则回复总数应该是4,而不是1。因为所有记录都是Comment ID(1)的子记录。同样,如果选择评论 ID (2),则计数为 3。

这是我已经完成的查询:

Comment::query()
    ->without('post')
    ->with('user:id,name,email,role,picture')
    ->withCount('replies')
    ->where('parent_comment_id', request()->input('comment_id', null))
    ->where('post_id', $id)
    ->orderByDesc('replies_count')
    ->paginate(2)
    ->withQueryString()
    ->fragment('post-comments');

现在如何显示评论的总回复数?

laravel eloquent relationship query-builder
1个回答
0
投票

您可以尝试使用像 staudenmeir/laravel-adjacency-list 这样的包,它允许您定义递归关系。

class Comment extends Model
{
    use \Staudenmeir\LaravelAdjacencyList\Eloquent\HasRecursiveRelationships;

    public function getParentKeyName()
    {
        return 'parent_comment_id';
    }

    public function recursiveReplies()
    {
        return $this->hasManyOfDescendants(Comment::class);
    }
}

Comment::withCount('recursiveReplies')->get();
© www.soinside.com 2019 - 2024. All rights reserved.