How to select specific fields including withCount

Viewed 651

I'm trying to return specific columns including the reviews_count one.

Here is the non-optimized query (working):

Model::withCount('reviews')->get();

Here is what I try to achieve (doesn't work):

Model::withCount('reviews')->select('id','name','reviews_count')->get();

What should I do to include the reviews_count in the select query using eloquent?

1 Answers

withCount will add another custom select, so you don't need to add it in to your select method. Just put select before withCount like below:

Model::select('id','name')->withCount('reviews')->get();

above will generate below query:

select "id", "name", (select count(*) from "reviews" where "invoices"."id" = "reviews"."invoice_id") as "reviews_count" from "invoices" 

if you put select method after other select like withCount it will be overridden or replaced. another way use addSelect method, but you still need to remove the default select like below

Model::select([])->withCount('reviews')->addSelect('id','name')->get();
Related