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. protected $guarded = [];
  13. public function user(): BelongsTo
  14. {
  15. return $this->belongsTo(User::class);
  16. }
  17. public function node(): BelongsTo
  18. {
  19. return $this->belongsTo(Node::class);
  20. }
  21. // 用户每时使用总流量
  22. public function scopeUserHourly($query, $uid)
  23. {
  24. return $query->whereUserId($uid)->whereNodeId(null);
  25. }
  26. public function scopeUserRecentUsed($query, $uid)
  27. {
  28. return $query->userHourly($uid)->where('created_at', '>=', date('Y-m-d H:i:s', time() - 3900));
  29. }
  30. // 1小时内流量异常用户
  31. public function trafficAbnormal(): array
  32. {
  33. $userTotalTrafficList = self::whereNodeId(null)
  34. ->where('total', '>', MB * 50)
  35. ->where('created_at', '>=', date('Y-m-d H:i:s', time() - 3900))
  36. ->groupBy('user_id')
  37. ->selectRaw('user_id, sum(total) as totalTraffic')->pluck('totalTraffic', 'user_id')
  38. ->toArray(); // 只统计50M以上的记录,加快速度
  39. foreach ($userTotalTrafficList as $user => $traffic) {
  40. if ($traffic > sysConfig('traffic_ban_value') * GB) {
  41. $result[] = $user;
  42. }
  43. }
  44. return $result ?? [];
  45. }
  46. }