LogGamecardClick.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace App\Game;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Carbon\Carbon;
  5. class LogGamecardClick extends Model
  6. {
  7. protected $connection = 'mysql'; // 如果使用非默认连接,指定连接名称
  8. protected $table = 'webgame.log_gamecard_click';
  9. public $timestamps = false; // 表中没有 Laravel 自动管理的时间戳字段
  10. protected $fillable = [
  11. 'gameid',
  12. 'UserID',
  13. 'create_at'
  14. ];
  15. /**
  16. * 记录日志
  17. *
  18. * @param int $gameid
  19. * @param int $userId
  20. * @return LogGamecardClick
  21. */
  22. public static function recordClick($gameid, $userId)
  23. {
  24. return self::create([
  25. 'gameid' => $gameid,
  26. 'UserID' => $userId,
  27. 'create_at' => Carbon::now()
  28. ]);
  29. }
  30. /**
  31. * 统计最近一周内根据 gameid 返回条数
  32. *
  33. * @return \Illuminate\Support\Collection
  34. */
  35. public static function getWeeklyStats()
  36. {
  37. $oneWeekAgo = Carbon::now()->subWeek();
  38. return self::select('gameid', \DB::raw('COUNT(*) as clicks'))
  39. ->where('create_at', '>=', $oneWeekAgo)
  40. ->groupBy('gameid')
  41. ->orderBy('clicks', 'desc')
  42. ->get();
  43. }
  44. public static function getWeeklyStatsByBrand()
  45. {
  46. $oneWeekAgo = Carbon::now()->subWeek();
  47. // 获取最近一周点击数量最多的游戏
  48. $gameClicks = self::select('gameid', \DB::raw('COUNT(*) as clicks'))
  49. ->where('create_at', '>=', $oneWeekAgo)
  50. ->groupBy('gameid')
  51. ->orderBy('clicks', 'desc')
  52. ->get();
  53. // 获取游戏详细信息
  54. $gameIdsAll = $gameClicks->pluck('gameid')->toArray();
  55. $games = GameCard::whereIn('id', $gameIdsAll)->where('state','<>',0)->get()->keyBy('id');
  56. // 按品牌分类,确保每个品牌最多返回16个游戏
  57. $result = [];
  58. foreach ($gameClicks as $click) {
  59. $game = $games->get($click->gameid);
  60. if ($game) {
  61. if (!isset($result[$game->brand])) {
  62. $result[$game->brand] = [];
  63. }
  64. if (count($result[$game->brand]) < 15) {
  65. $result[$game->brand][] = $game->id;
  66. }
  67. }
  68. }
  69. // 将结果格式化为 "brand: gameid, gameid, ..."
  70. foreach ($result as $brand => $gameIds) {
  71. $result[$brand] = implode(', ', $gameIds);
  72. }
  73. $result['ALL']=$gameIdsAll;//implode(', ', array_slice(,0,16));
  74. return $result;
  75. }
  76. }