trafficmonitor/app/Models/CollectorModel.php

78 lines
2.4 KiB
PHP

<?php
namespace App\Models;
use App\Entities\CollectorEntity;
use App\Entities\TrafficEntity;
class CollectorModel extends CommonModel
{
const TABLE = "collectorinfo";
const PK = "uid";
const TITLE = "uid";
protected $table = self::TABLE;
// protected $useAutoIncrement = false;
protected $primaryKey = self::PK;
protected $returnType = CollectorEntity::class;
protected $allowedFields = [
"uid",
"trafficinfo_uid",
"in",
"out",
"raw_in",
"raw_out",
"updated_at"
];
public function __construct()
{
parent::__construct();
}
public function getLastEntity($uid): CollectorEntity|null
{
return $this
->where('trafficinfo_uid', $uid)
->orderBy('created_at', 'DESC')
->first(); // 첫 번째 레코드(=가장 최신)
}
/**
* DESC 기준 95% + 1번째 값을 가져오는 함수
*
* @param string $field in_kbits 또는 out_kbits
* @param string $startDate '2024-10-01'
* @param string $endDate '2024-10-30'
* @return mixed 해당 자리의 수치값
*/
public function get95PercentileValue(TrafficEntity $trafficEntity, string $field, string $startDate, string $endDate)
{
// 1) 해당 조건의 전체 개수 구하기
$total =
$this->where("trafficinfo_uid", $trafficEntity->getPK())
->where("created_at >=", $startDate)
->where("created_at <=", $endDate)
->countAllResults(true); // true해야 queryu reset 함
// false = 쿼리 빌더 초기화 X
if ($total === 0) {
return null;
}
// 2) index = floor(total * 0.95) + 1
$index = floor($total * 0.95) + 1;
// 3) 95% + 1 번째 값 조회
$builder = $this->builder();
$builder->select($field)
->where("trafficinfo_uid", $trafficEntity->getPK())
->where("created_at >=", $startDate)
->where("created_at <=", $endDate)
->orderBy($field, "DESC")
->limit(1, $index - 1); // LIMIT offset, 1
// 🔥 실행되기 전에 SQL 확인
$sql = $builder->getCompiledSelect(false); //반드시 false해야 queryu reset 않함
log_message('debug', '[95PERCENTILE QUERY] ' . $sql);
$row = $builder->get()->getRowArray();
return $row[$field] ?? null;
}
}