ThinkPHP中模型字段如何实现自动填充创建和更新时间戳?

2026-04-30 11:281阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计881个文字,预计阅读时间需要4分钟。

ThinkPHP中模型字段如何实现自动填充创建和更新时间戳?

ThinkPHP+6+的模型时间戳是opt-in机制,默认不启用。需要显式开启时间戳功能,并且确保字段名、类型、配置三者对应正确。

  • 必须在模型类中设置 protected $autoWriteTimestamp = true;(或具体指定 'datetime' / 'int'
  • 字段名默认是 create_timeupdate_time,若数据库用的是 createTime,需同步改 protected $createTime = 'createTime';protected $updateTime = 'updateTime';
  • createTime 只在 save() 且主键为空(即新增)时触发;updateTimesave() 且主键存在时更新——但手动调用 update() 静态方法时,默认不走模型时间戳逻辑,得加 ['force' => true]

为什么 save(['id' => 1, 'name' => 'xxx']) 没更新 updateTime

因为 ThinkPHP 默认只对「模型实例的属性变更」做时间戳感知,直接传数组给 save() 会跳过属性赋值流程,导致 updateTime 不被识别为待更新字段。

阅读全文
标签:PHPThinkPHP

本文共计881个文字,预计阅读时间需要4分钟。

ThinkPHP中模型字段如何实现自动填充创建和更新时间戳?

ThinkPHP+6+的模型时间戳是opt-in机制,默认不启用。需要显式开启时间戳功能,并且确保字段名、类型、配置三者对应正确。

  • 必须在模型类中设置 protected $autoWriteTimestamp = true;(或具体指定 'datetime' / 'int'
  • 字段名默认是 create_timeupdate_time,若数据库用的是 createTime,需同步改 protected $createTime = 'createTime';protected $updateTime = 'updateTime';
  • createTime 只在 save() 且主键为空(即新增)时触发;updateTimesave() 且主键存在时更新——但手动调用 update() 静态方法时,默认不走模型时间戳逻辑,得加 ['force' => true]

为什么 save(['id' => 1, 'name' => 'xxx']) 没更新 updateTime

因为 ThinkPHP 默认只对「模型实例的属性变更」做时间戳感知,直接传数组给 save() 会跳过属性赋值流程,导致 updateTime 不被识别为待更新字段。

阅读全文
标签:PHPThinkPHP