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

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']

Last updated