This commit is contained in:
2026-03-05 16:50:52 +08:00
parent 39955a17a8
commit aef404548d
4 changed files with 106 additions and 59 deletions

View File

@@ -35,6 +35,12 @@ class BaseModel extends Model implements ModelInterface
*/
protected $updateTime = 'update_time';
/**
* 自动写入时间戳(创建时写 create_time更新时写 update_time
* @var bool
*/
protected $autoWriteTimestamp = true;
/**
* 隐藏字段
* @var array
@@ -94,24 +100,48 @@ class BaseModel extends Model implements ModelInterface
}
/**
* 新增前事件
* 新增前事件:自动写入 create_time有后台登录信息时写入 created_by
* @param Model $model
* @return void
*/
public static function onBeforeInsert($model): void
{
$info = getCurrentInfo();
$info && $model->setAttr('created_by', $info['id']);
$createTime = $model->createTime ?? 'create_time';
if ($createTime && !$model->getData($createTime)) {
$model->set($createTime, date('Y-m-d H:i:s'));
}
if (function_exists('getCurrentInfo')) {
$info = getCurrentInfo();
if (!empty($info['id'])) {
try {
$model->setAttr('created_by', $info['id']);
} catch (\Throwable $e) {
}
}
}
}
/**
* 写入前事件
* 写入前事件:更新时自动写入 update_time有后台登录信息时写入 updated_by
* @param Model $model
* @return void
*/
public static function onBeforeWrite($model): void
{
$info = getCurrentInfo();
$info && $model->setAttr('updated_by', $info['id']);
if ($model->isUpdate()) {
$updateTime = $model->updateTime ?? 'update_time';
if ($updateTime) {
$model->set($updateTime, date('Y-m-d H:i:s'));
}
}
if (function_exists('getCurrentInfo')) {
$info = getCurrentInfo();
if (!empty($info['id'])) {
try {
$model->setAttr('updated_by', $info['id']);
} catch (\Throwable $e) {
}
}
}
}
}