Hamid Ali
Hamid Ali

Reputation: 304

Append Relation Count while using select in eloquent query

So i have a query where i want to select specific columns and relation count on a model.

Something like this

$posts = Post::withCount('comments')->select('title', 'content')->get();

foreach ($posts as $post) {
    $post->comments_count // this is not available because of select in query
}

Now when I use select in the query comments_count is no longer available. There is $appends option on the model where I can do something like $appends = ['comments_count'] on the Post model but it will not work. Any idea how to append the data and use the select on model while querying using eloquent.

there is $withCount option on the model as well but it will lazy load while querying comments with post (i.e. inverse relation query).

Upvotes: 0

Views: 422

Answers (1)

IGP
IGP

Reputation: 15786

The problem if that withCount('comments') will generate the comments_count for each post.

Also, the select() overrides the previous withCount(). Simply change the order.

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

If you want the global count, you'll need to use a collection method to sum all the counts.

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

Upvotes: 1

Related Questions