Visit.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Http\Request;
  6. class Visit extends Model
  7. {
  8. protected $table = 'visits';
  9. protected $primaryKey = 'id';
  10. public $keyType = 'int';
  11. public $incrementing = true;
  12. public $timestamps = true;
  13. const CREATED_AT = 'created_at';
  14. const UPDATED_AT = null;
  15. const DELETED_AT = null;
  16. protected $guarded = [];
  17. /**
  18. * 방문자 수 등록
  19. */
  20. public function register(Request $request): ?\Shetabit\Visitor\Models\Visit
  21. {
  22. return visitor()->visit($request->user());
  23. }
  24. /**
  25. * 오늘 방문자 수
  26. */
  27. public function todayCount(): int
  28. {
  29. return $this->whereDate('created_at', now()->today())->distinct()->count('ip');
  30. }
  31. /**
  32. * 어제 방문자 수
  33. */
  34. public function yesterdayCount(): int
  35. {
  36. return $this->whereDate('created_at', now()->yesterday())->distinct()->count('ip');
  37. }
  38. /**
  39. * 누적 방문자 수
  40. */
  41. public function totalCount(): int
  42. {
  43. $sql = "
  44. SELECT SUM(`CNT`) AS `total` FROM (
  45. SELECT COUNT(DISTINCT `ip`) AS CNT FROM `visits` WHERE 1 GROUP BY DATE_FORMAT(created_at, '%Y%m%d')
  46. ) D;
  47. ";
  48. return DB::selectOne($sql)->total;
  49. }
  50. }