【问题标题】:Laravel withCount of all comments and child commentsLaravel withCount 所有评论和子评论
【发布时间】:2021-02-20 06:21:00
【问题描述】:

我正在使用 Laravel 8 和 withCount 属性来获取在我的产品模型上发布的所有 cmets 的数量。这些 cmets 也有子 cmets。现在我想获取每个产品的已发布 cmets 和子 cmets 的数量...

我的评论表: id, page_status_id, user_id, commentable_type, commentable_id, content

我的孩子 cmets 表: id, page_status_id, user_id, comment_id, content

这是我 product 模型中的 comments 关系:

    public function comments()
    {
        return $this->morphMany('App\Models\Comment', 'commentable')->orderBy('id');
    }

这是我的withCount 函数:

    public function publishedComments()
    {
        return $this->comments()->where('page_status_id', PageStatus::getIdByStatus('publish'));
    }

获取已发布 cmets 的计数非常容易...但是如何获取某个产品的所有已发布 cmets 和子 cmets 的计数?

有什么想法吗?我用inner join 尝试了一个原始的 SQL 语句,但这也是错误的方式..

诚挚的问候和感谢

【问题讨论】:

  • 您可以使用其他查询吗?我可以告诉你一个得到你需要的查询。但需要单独查询
  • 什么意思?请发一个例子

标签: mysql laravel eloquent count nested


【解决方案1】:

您应该构建一个递归关系查询。 在递归查询中,您尝试选择所有子项及其后代。这方面的一个例子是回答 here 雄辩。

当您尝试计算孩子的孩子时,您需要访问后代。 在下面的代码中,我试图通过 (allComments) 函数递归地查询关系。这意味着,您可以获得所有父母和孩子的 cmets。在这里,您通过调用with 并传递allComments 方法来创建递归函数。

public function comments()
{
    return $this->morphMany('App\Models\Comment', 'commentable')->orderBy('id');
}

public function allComments()
{
    return $this->comments()->with('allComments');
}

您可以陪伴allCommentsProduct::withCount('allComments') 等关系计数

【讨论】:

  • 我无法理解您的回答。您能否发布更详细的答案?
  • 是的,但请告诉我答案的含糊之处。
  • 你正在使用->with('allComments') 这意味着allComments 需要是一个关系,对吧?!?但你还没有定义这种关系?
  • 答案已更新。提供了一个链接以作进一步说明。
猜你喜欢
  • 2020-01-09
  • 1970-01-01
  • 1970-01-01
  • 2015-04-17
  • 2016-11-30
  • 2018-08-16
  • 2017-07-29
  • 2018-12-15
  • 1970-01-01
相关资源
最近更新 更多