SELECT SPECIFIC COLUMNS WITH RELATIONSHIP COUNT
Mar 01, 2024 Copy Link
I was shocked by the result when I attempted to get the post count of each user using the withCount method and then specified the columns I needed. So, lemme present the code that I wrote in this case:
use App\Models\User;
User::withCount('posts')
->select(['name', 'id'])
->get();
The previous code delivered a null value of the `posts_count`
attribute and when I dumped the query I found that the `select`
method overrides the result of the `withCount`
method:
use App\Models\User;
User::withCount('posts')
->select(['name', 'id'])
->toSql();
The triggered query against the database was:
select `name`, `id` from `users`
As illustrated in the query that no place for the `posts_count`
so, I have made a little change to fix that issue:
use App\Models\User;
User::select(['name', 'id'])
->withCount('posts')
->get();
This change will execute a different query against the database:
select `name`, `id`, (select count(*) from `posts` where `users`.`id` = `posts`.`user_id`) as `posts_count` from `users`
Boom..we got a hit 🏒