UserHourlyDataFlow.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  5. /**
  6. * 用户流量每小时统计
  7. */
  8. class UserHourlyDataFlow extends Model
  9. {
  10. public const UPDATED_AT = null;
  11. protected $table = 'user_hourly_data_flow';
  12. public function user(): BelongsTo
  13. {
  14. return $this->belongsTo(User::class);
  15. }
  16. public function node(): BelongsTo
  17. {
  18. return $this->belongsTo(Node::class);
  19. }
  20. // 用户每时使用总流量
  21. public function scopeUserHourly($query, $uid)
  22. {
  23. return $query->whereUserId($uid)->whereNodeId(null);
  24. }
  25. public function scopeUserRecentUsed($query, $uid)
  26. {
  27. return $query->userHourly($uid)->where('created_at', '>=', date('Y-m-d H:i:s', time() - 3900));
  28. }
  29. // 1小时内流量异常用户
  30. public function trafficAbnormal(): array
  31. {
  32. $userTotalTrafficList = self::whereNodeId(null)
  33. ->where('total', '>', MB * 50)
  34. ->where('created_at', '>=', date('Y-m-d H:i:s', time() - 3900))
  35. ->groupBy('user_id')
  36. ->selectRaw('user_id, sum(total) as totalTraffic')->pluck('totalTraffic', 'user_id')
  37. ->toArray(); // 只统计50M以上的记录,加快速度
  38. foreach ($userTotalTrafficList as $user => $traffic) {
  39. if ($traffic > sysConfig('traffic_ban_value') * GB) {
  40. $result[] = $user;
  41. }
  42. }
  43. return $result ?? [];
  44. }
  45. }