在雄辩查询中使用select时附加关系计数



所以我有一个查询,我想在其中选择模型上的特定列和关系计数。

像这样的

$posts = Post::withCount('comments')->select('title', 'content')->get();
foreach ($posts as $post) {
$post->comments_count // this is not available because of select in query
}

现在,当我在查询中使用select时,comments_count不再可用。模型上有$appends选项,我可以在Post模型上做类似$appends = ['comments_count']的事情,但它不起作用。任何关于如何在使用雄辩器进行查询时附加数据并使用select on模型的想法。

模型上也有CCD_ 4选项,但在用post查询评论时会延迟加载(即反向关系查询(。

如果withCount('comments')将为每个帖子生成comments_count的问题。

此外,select()会覆盖先前的withCount()。只需更改顺序。

$posts = Post::select('title', 'content')->withCount('comments')->get();
foreach ($posts as $post) {
echo $post->comments_count;
}

如果您想要全局计数,则需要使用collection方法对所有计数求和。

echo $posts->sum('comments_count');

最新更新