代码之家  ›  专栏  ›  技术社区  ›  Bruno Francisco

伴随递归查询的withcount雄辩

  •  0
  • Bruno Francisco  · 技术社区  · 6 年前

    我正在尝试检索一条评论有说服力的回复数 withCount() . 到目前为止,我已经定义了以下关系:

    指标体系

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

    使用 计数()

    $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! 我猜可能是因为递归调用 计数() 可能正在做。隧道尽头的任何光线都会很好。提前谢谢你

    3 回复  |  直到 6 年前
        1
  •  0
  •   Palak Jadav    6 年前

    使用查询中的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
  •   Mohammad Khan    6 年前

    改变 ->withCount('replies'); ->with('replies')->count();

    编辑

    如果您想用非空的回复ID来计算数据

    改变 ->withcount(“回复”);

    ->with(['replies'=>function($query){$query->where('reply_id','!=','NULL')->get();}])->count();
    
        3
  •  0
  •   Bruno Francisco    6 年前

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

    在我的模型中,我插入了:

    protected $withCount = [
            'replies'
        ];
    

    事实上,这是不必要的。我只需要调用函数 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');