Aggregation dan Statistik
NexaModel documentation.
NexaModel · Storage() · NexaDb
$this->Storage('news')->where()->first();Basic Aggregation
Count
// Count semua records
$total = $this->Storage('users')->count();
// Count dengan kondisi
$activeUsers = $this->Storage('users')
->where('status', 'active')
->count();
// Count kolom tertentu
$emailCount = $this->Storage('users')->count('email');
Sum
// Sum kolom
$totalPoints = $this->Storage('users')->sum('points');
// Sum dengan kondisi
$activeUserPoints = $this->Storage('users')
->where('status', 'active')
->sum('points');
Average
$averageAge = $this->Storage('users')->avg('age');
Min/Max
$minAge = $this->Storage('users')->min('age');
$maxAge = $this->Storage('users')->max('age');
Advanced Aggregation
Count by Conditions
$stats = $this->Storage('users')
->countByConditions('status', [
'active' => ['status', '=', 'active'],
'inactive' => ['status', '=', 'inactive'],
'banned' => ['status', '=', 'banned']
]);
// Result: ['active' => 150, 'inactive' => 25, 'banned' => 5]
Count with Percentage
$stats = $this->Storage('users')
->countWithPercentage('status', ['active', 'inactive']);
// Result:
// [
// 'active' => ['count' => 150, 'percentage' => 85.7],
// 'inactive' => ['count' => 25, 'percentage' => 14.3]
// ]
Count by Group
$stats = $this->Storage('users')
->countByGroup('department');
// Result: ['IT' => 50, 'HR' => 20, 'Finance' => 30]
Multiple Column Aggregation
$stats = $this->Storage('orders')
->countColumns(['status', 'payment_method']);
// Result:
// [
// 'status' => ['completed' => 100, 'pending' => 20],
// 'payment_method' => ['credit_card' => 80, 'paypal' => 40]
// ]
Sum with Percentage
$stats = $this->Storage('orders')
->sumColumnsWithPercentage(['total_amount', 'tax_amount']);
// Result:
// [
// 'total_amount' => ['sum' => 50000, 'percentage' => 90.9],
// 'tax_amount' => ['sum' => 5000, 'percentage' => 9.1]
// ]
Lanjut
Topik sebelumnya: Operasi CRUD. Topik berikutnya: Pagination. Lihat juga Models, Events, Helper & template, daftar dokumentasi.