thinkphp5.1中restore()不更新update_time是正常行为,因其仅将delete_time设为null,未触发时间戳自动写入机制;需手动赋值update_time后再save或直连db更新。

ThinkPHP5.1 中调用 restore() 恢复软删除数据后,update_time(或自定义的更新时间字段)不自动更新,这是正常行为——因为 restore() 本质是将 delete_time 设为 NULL 的 UPDATE 操作,并未触发模型的「更新时间自动写入」逻辑。
为什么 restore 不更新 updateTime
源码中 restore() 方法直接执行 $this->save(),但此时模型处于「已存在、非新增、非常规更新」状态,且框架未在该流程中主动调用时间戳写入机制。它只改 delete_time,其余字段保持原样,包括 update_time。
手动补全 update_time 的推荐方式
恢复时需显式更新时间戳字段,以下方法安全可靠:
-
方式一:恢复后立即 save() 并指定更新字段
$user = User::onlyTrashed()->find(123);
$user->restore();
$user->update_time = date('Y-m-d H:i:s'); // 或 time()
$user->save(); -
方式二:一步完成(推荐)
$user = User::onlyTrashed()->find(123);
$user->delete_time = null;
$user->update_time = date('Y-m-d H:i:s');
$user->save();
这绕过了restore()内部逻辑,完全可控。 -
方式三:用 Db 类直更新(无事件,轻量)
\think\Db::name('user')
->where('id', 123)
->update(['delete_time' => null, 'update_time' => date('Y-m-d H:i:s')]);
避免踩坑的关键点
确保模型中正确配置了自动时间戳,否则即使手动赋值也可能被忽略:
- 模型内必须声明:
protected $autoWriteTimestamp = true;
protected $updateTime = 'update_time'; // 与数据库字段名严格一致 - 数据库字段类型应为
DATETIME或TIMESTAMP,且允许NULL(update_time字段本身通常不允许 NULL,但需能正常接收新值) - 不要依赖
allowField白名单遗漏update_time,否则手动赋值会被过滤掉
如果想全局统一处理 restore 行为
可在模型中重写 restore() 方法(继承并扩展),例如:
{
$this->update_time = $this->autoWriteTimestamp($this->updateTime);
return parent::restore();
}
注意:需确保 $this->autoWriteTimestamp() 可被外部调用,或直接使用 date('Y-m-d H:i:s') 更稳妥。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











