laravel - 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()
可能正在执行的递归调用。隧道尽头的任何光线都会很棒。先感谢您
解决方案
老实说,这对我来说是一个愚蠢的错误。我正在检查旧版本 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');
推荐阅读
- audio - 在 nim 中使用 sdl2/mixer 播放音频的时间不可靠
- web - Nginx 将所有内容重定向到 www https
- javascript - 当我在完整日历中滚动时如何制作固定的左栏?
- spring - Spring : Autowire
- python - 计算总和可被 k 整除的所有子数组
- php - button should display only if we support order's zipcode
- javascript - 角度材料日期选择器返回 Moment 对象而不是 Date
- cassandra - 如何在 openshift 中运行作业以安排特定脚本?
- python - Nested Serializer Problem in showing reverse
- svelte - Firing events from a svelte component and hearing it from containing page