首页 > 解决方案 > withCount 和递归查询 Eloquent

问题描述

我正在尝试使用 Eloquent 检索评论的回复数withCount()。到目前为止,我已经定义了以下关系:

报价评论

protected $withCount = [
        'replies'
    ];

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

使用withCount()

$quoteComments = QuotesComments::where('quote_id', $quoteid)
            ->whereNull('reply_id') // We don't want to show comments that are reply to other comments
            ->orderBy('votes', 'DESC')
            ->withCount('replies');

数据库方案:

id   quote_id   reply_id 
1    2          NULL
2    2          1

我收到了Maximum function nesting level of '512' reached, aborting!我猜测的错误,可能是由于withCount()可能正在执行的递归调用。隧道尽头的任何光线都会很棒。先感谢您

标签: laraveleloquent

解决方案


老实说,这对我来说是一个愚蠢的错误。我正在检查旧版本 Laravel 的文档并与最新版本(5.7)混合。

发生的事情是在我的模型中插入:

protected $withCount = [
        'replies'
    ];

实际上没有必要。我只需要调用withCount()Controller 中的函数,最终结果只有:

$quoteComments = QuotesComments::where('quote_id', $quoteid)
            ->whereNull('reply_id') // We don't want to show comments that are reply to other comments
            ->orderBy('votes', 'DESC')
            ->withCount('replies');

推荐阅读