Files
2026-09-24 22:02:06 +08:00

114 lines
2.3 KiB
PHP

<?php
namespace app\common\model\data;
use think\Model;
class Logs extends Model
{
// 表名
protected $name = 'data_logs';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'integer';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
protected $deleteTime = false;
// 追加属性
protected $append = [
];
protected $type = [
];
// JSON 字段统一处理:读取时输出 JSON 字符串,写入时接受数组或 JSON 字符串
public function getBeforeDataAttr($value)
{
return $this->stringifyJsonData($value);
}
public function getAfterDataAttr($value)
{
return $this->stringifyJsonData($value);
}
public function setBeforeDataAttr($value)
{
return $this->normalizeJsonData($value);
}
public function setAfterDataAttr($value)
{
return $this->normalizeJsonData($value);
}
/**
* 将数据库值转换为可展示的 JSON 字符串
*/
protected function stringifyJsonData($value)
{
$flag = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT;
if (is_array($value)) {
return empty($value) ? '' : json_encode($value, $flag);
}
$value = $value === null ? '' : trim((string)$value);
if ($value === '') {
return '';
}
$decoded = json_decode($value, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return $value;
}
return json_encode($decoded, $flag);
}
/**
* 将输入(数组或 JSON 字符串)规范化为存储的 JSON 字符串
*/
protected function normalizeJsonData($value)
{
$flag = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
if (is_array($value)) {
return json_encode($value, $flag);
}
$value = $value === null ? '' : trim((string)$value);
if ($value === '') {
return '';
}
$decoded = json_decode($value, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return json_encode([$value], $flag);
}
return json_encode($decoded, $flag);
}
}