我想获取注释计数,而不是在单个查询中获取所有注释, 我正在使用以下代码,但出现错误
$answers = Answers::project([
'comments'=>0,
'comments_count' => [
'$size' => '$comments'
]])
->where('question_id',$request->question_id)
->get();
错误:-“消息”:“不支持的投影选项:comments_count:{$ size:\” comments \“}”,
jenssegers mongodb laravel软件包中的$ size聚合支持吗? 如果是,那是使用它的正确方法,
谢谢。
答案 0 :(得分:0)
取决于本文https://laravel.com/docs/5.7/eloquent-relationships
您可以使用withCount
在Project
模型中,您可以添加protected
变量withCount
protected $withCount = ['comments'];
//comments is function name of relation between project and comments
将返回comments_count
答案 1 :(得分:0)
您可以使用汇总运行原始查询,请在下面的查询中进行检查
$answers = Answers::raw(function($collection) use ($request) {
return $collection->aggregate([
[
'$match' => [
'question_id' => $request->question_id
]
],
[
'$project' => [
'answer'=>1,
'user'=>1,
'comment_count' => [
'$size' => [
'$ifNull'=> ['$comments', []]
]
]
]
]
]);
});
这是在laravel 5.6中使用jensseger mongodb的有效查询。