Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

iamarbabhussain's avatar

WithCount and WithAvg both in a query

How can i use withCount and withAvg both inside a query? I want reviews count and avg for all users.

0 likes
7 replies
s4muel's avatar
s4muel
Best Answer
Level 50
//relation in Product
public function reviews()
{
    return $this->hasMany(Review::class);
}

//query
Product::withCount('reviews')->withAvg('reviews', 'rating')->get();
2 likes
s4muel's avatar

this is the query it generates:

select "product".*, (select count(*) from "review" where "product"."id" = "review"."product_id") as "review_count", (select avg("review"."rating") from "review" where "product"."id" = "review"."product_id") as "review_avg_rating" from "product"
1 like
SilenceBringer's avatar

@iamarbabhussain you can try the way suggested by @s4muel and another way - join the table and add 2 aggregation columns in select for this join, and see which one will works faster in your way

1 like
iamarbabhussain's avatar

okay cool. thanks for your time man! i'll mark @s4muel answer as best because of specificity with my question but your answer is also great.

Please or to participate in this conversation.