GameEnterLogController.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\GameEnterLog;
  5. use Illuminate\Http\Request;
  6. use Illuminate\Support\Facades\DB;
  7. class GameEnterLogController extends Controller
  8. {
  9. /**
  10. * Average game enter duration statistics per game.
  11. */
  12. public function statistics(Request $request)
  13. {
  14. $startDate = $request->input('start_date', date('Y-m-d', strtotime('-7 days')));
  15. $endDate = $request->input('end_date', date('Y-m-d'));
  16. $rows = DB::table(GameEnterLog::TABLE)
  17. ->whereBetween('log_date', [$startDate, $endDate])
  18. ->selectRaw('game_id, COUNT(*) as enter_count, AVG(CAST(duration_ms AS FLOAT)) as avg_duration_ms')
  19. ->groupBy('game_id')
  20. ->orderByDesc('enter_count')
  21. ->get();
  22. $gameIds = $rows->pluck('game_id')->filter()->unique()->values()->toArray();
  23. $games = [];
  24. if (!empty($gameIds)) {
  25. $gamesData = DB::connection('mysql')
  26. ->table('webgame.games')
  27. ->whereIn('id', $gameIds)
  28. ->select('id', 'brand', 'title')
  29. ->get();
  30. foreach ($gamesData as $game) {
  31. $games[$game->id] = $game;
  32. }
  33. }
  34. $statistics = [];
  35. foreach ($rows as $row) {
  36. $gameId = (int) $row->game_id;
  37. $avgMs = (float) $row->avg_duration_ms;
  38. $gameName = __('auto.未知游戏');
  39. if (isset($games[$gameId])) {
  40. $game = $games[$gameId];
  41. $gameName = $game->brand . ' - ' . $game->title;
  42. }
  43. $statistics[] = [
  44. 'game_id' => $gameId,
  45. 'game_name' => $gameName,
  46. 'enter_count' => (int) $row->enter_count,
  47. 'avg_duration_ms' => round($avgMs, 2),
  48. 'avg_duration_sec' => round($avgMs / 1000, 3),
  49. ];
  50. }
  51. return view('admin.game_enter_log.statistics', [
  52. 'statistics' => $statistics,
  53. 'start_date' => $startDate,
  54. 'end_date' => $endDate,
  55. ]);
  56. }
  57. }