📕
Sprnva Docs
  • Introduction
  • What's New?
  • Installation
    • Requirements
    • Download Sprnva zip no composer required
    • Install Sprnva Using Composer
    • Setup Config
  • Deployment
  • File Structure
  • Database
    • Select
    • SelectLoop
    • Insert
    • Update
    • Delete
    • Query
    • Seeder
    • Paginate
    • With
    • andFilter
    • withCount
    • get
  • Query Builder
  • Migration
    • INSTANCES
      • NEW
      • RENAMETABLE
      • DROP
      • CHANGE
    • DUMPS
      • dump
      • dump prune
    • MAKE
    • MIGRATE
      • migrate
      • migrate fresh
    • ROLLBACK
  • Routing
    • with parameter
    • multiple parameters
    • with closure
    • group
    • controller grouping
  • Controllers
    • methods
  • Views
    • Passing Parameters
  • Validation
    • validate
      • validation type
  • Authentication
  • Alert Messages
  • Default Helpers
  • CSRF Protection
  • Email
  • Packages
    • Fortify
  • Themes and Templates
Powered by GitBook
On this page
  1. Database

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

PreviousandFilterNextget

Last updated 2 years ago