withCount和递归查询

时间:2019-02-10 23:13:40

标签: laravel eloquent

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

QuoteComments

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()正在执行的递归调用所致。隧道尽头的任何灯光都会很棒。预先谢谢你

3 个答案:

答案 0 :(得分:0)

->withCount('replies');更改为->with('replies')->count();

编辑

如果您要对不为null的数据进行计数reply_id

更改   ->withCount('replies');

->with(['replies'=>function($query){$query->where('reply_id','!=','NULL')->get();}])->count();

答案 1 :(得分:0)

在查询中使用whereHas不考虑没有答复的评论。它只会返回至少有一个重播的评论。

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

答案 2 :(得分:0)

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

发生了什么事,我正在插入模型:

protected $withCount = [
        'replies'
    ];

实际上没有必要。我只需要在Controller中调用函数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');