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 🏒

Share via

Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.

Most recent

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using...

    FREE

  • What is SQL Injection

    What is SQL Injection

    FREE

  • Leveraging virtual generated columns in MySQL using Laravel

    Leveraging virtual generated col...

    FREE