From 2d538c15de939c073b92caa3b63170f1eb67d54d Mon Sep 17 00:00:00 2001 From: xboard Date: Wed, 11 Mar 2026 07:01:19 +0800 Subject: [PATCH] perf: fix getTrafficRank slow query with index and batch loading --- .../Controllers/V2/Admin/StatController.php | 15 +++++++------ ...1_000002_add_stat_user_record_at_index.php | 22 +++++++++++++++++++ 2 files changed, 30 insertions(+), 7 deletions(-) create mode 100644 database/migrations/2026_03_11_000002_add_stat_user_record_at_index.php diff --git a/app/Http/Controllers/V2/Admin/StatController.php b/app/Http/Controllers/V2/Admin/StatController.php index e7d615c..805fa94 100644 --- a/app/Http/Controllers/V2/Admin/StatController.php +++ b/app/Http/Controllers/V2/Admin/StatController.php @@ -481,19 +481,20 @@ class StatController extends Controller } $result = []; + $ids = $currentData->pluck('id'); + $names = $type === 'node' + ? Server::whereIn('id', $ids)->pluck('name', 'id') + : User::whereIn('id', $ids)->pluck('email', 'id'); + foreach ($currentData as $data) { $previousValue = isset($previousData[$data->id]) ? $previousData[$data->id]->value : 0; $change = $previousValue > 0 ? round(($data->value - $previousValue) / $previousValue * 100, 1) : 0; - $name = $type === 'node' - ? optional(Server::find($data->id))->name ?? "Node {$data->id}" - : optional(User::find($data->id))->email ?? "User {$data->id}"; - $result[] = [ 'id' => (string) $data->id, - 'name' => $name, - 'value' => $data->value, // Convert to GB - 'previousValue' => $previousValue, // Convert to GB + 'name' => $names[$data->id] ?? ($type === 'node' ? "Node {$data->id}" : "User {$data->id}"), + 'value' => $data->value, + 'previousValue' => $previousValue, 'change' => $change, 'timestamp' => date('c', $endDate) ]; diff --git a/database/migrations/2026_03_11_000002_add_stat_user_record_at_index.php b/database/migrations/2026_03_11_000002_add_stat_user_record_at_index.php new file mode 100644 index 0000000..2438855 --- /dev/null +++ b/database/migrations/2026_03_11_000002_add_stat_user_record_at_index.php @@ -0,0 +1,22 @@ +index(['record_at', 'user_id'], 'idx_stat_user_record_user'); + }); + } + + public function down(): void + { + Schema::table('v2_stat_user', function (Blueprint $table) { + $table->dropIndex('idx_stat_user_record_user'); + }); + } +};