trafficmonitor/app/Models/CommonModel.php
2025-11-14 17:41:28 +09:00

87 lines
2.8 KiB
PHP

<?php
namespace App\Models;
use CodeIgniter\Model;
abstract class CommonModel extends Model
{
protected $table = '';
protected $primaryKey = '';
protected $useAutoIncrement = true;
// protected $returnType = 'array';
//true이면 모든 delete * 메소드 호출은 실제로 행을 삭제하는 것이 아니라 플래그를 데이터베이스로 설정
protected $useSoftDeletes = false;
protected $protectFields = true;
protected $allowedFields = [];
protected bool $allowEmptyInserts = false;
protected bool $updateOnlyChanged = true;
protected array $casts = [];
protected array $castHandlers = [];
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
// Validation
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = ['_cleanNullsForDefaults']; //Field 값이 NULL일 경우 DB Default값 적용용
protected $afterInsert = [];
protected $beforeUpdate = ['_cleanNullsForDefaults']; //Field 값이 NULL일 경우 DB Default값 적용용
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
protected function __construct()
{
parent::__construct();
}
final public function getTable(): string
{
return constant("static::TABLE");
}
final public function getPKField(): string
{
return constant("static::PK");
}
final public function getTitleField(): string
{
return constant("static::TITLE");
}
final public function useAutoIncrement(): bool
{
return $this->useAutoIncrement;
}
// 이 훅은 save() 메서드 실행 시 자동으로 호출됩니다.
protected function _cleanNullsForDefaults(array $data): array
{
// $data['data'] 배열에 실제 INSERT/UPDATE 될 데이터가 들어있습니다.
if (!isset($data['data']) || !is_array($data['data'])) {
return $data;
}
// 데이터 배열을 순회하며 값이 null인 필드를 제거합니다.
foreach ($data['data'] as $key => $value) {
// 이 필드가 Primary Key가 아니면서 (PK는 Update 시 필요)
// 값이 null이면 DB에 명시하지 않도록 배열에서 제거합니다.
if ($key !== $this->primaryKey && $value === null) {
unset($data['data'][$key]);
}
}
return $data;
}
}