> For the complete documentation index, see [llms.txt](https://sprnva.gitbook.io/sprnva-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sprnva.gitbook.io/sprnva-docs/database/withcount.md).

# withCount

Sometimes we forgot the n+1 problem in developing and fetching datas in our application. This problem can cause tremendous amount of speed/memory consumption and creates a low performance application. Sprnva solve this problem using `withCount` method.

When using the `withCount` method this will count the total number of rows of the foreign table to the result set of the selected table.

Using this method is like saying as: `get this selected table "withCount" all the rows of it's selected foreign key`

```php
withCount([
    'relational-table' => [
        'foreign-id-in-the-selected-table',
        'primary-key-column-of-the-relational-table'
    ]
])

// using the withCount
Route::get('/withCount', function () {
    $users = DB()->selectLoop("*","users")
        ->withCount([
            "projects" => ['id', 'user_id']
        ])->get();

    foreach($users as $user){
        echo "Total Project of ".$user['fullname'].": ". $user['projects_count'];
    };
});
```

Take note that when retrieving the count of the realtional-table which is `projects` you can get it by concatenating or combining the `ralation-table` + `_count` like this `$user['projects_count']`

![](https://user-images.githubusercontent.com/37282871/197660256-f20e36b6-7fba-4e27-a6e7-6d82e21eccf3.png)
