系统支持自动写入创建和更新的时间戳字段(默认关闭),有两种方式配置支持。
全局开启,在数据库配置文件(config目录下的database.php)中进行设置:
// 开启自动写入时间戳字段 'auto_timestamp' => true,实例
<?php namespace app\index\model; use think\Model; class User extends Model { protected $autoWriteTimestamp = true; }又或者首先在数据库配置文件中全局开启,然后在个别不需要使用自动时间戳写入的模型类中单独关闭:
<?php namespace app\index\model; use think\Model; class User extends Model { protected $autoWriteTimestamp = false; }1、一旦配置开启的话,数据库会自动写入create_time和update_time两个字段的值。 如果不使用默认字段名的话需要在模型中设置,实例如下:
<?php namespace app\index\model; use think\Model; class User extends Model { // 定义时间戳字段名 protected $createTime = 'create_at'; protected $updateTime = 'update_at'; }2、两个字段默认为整型(int),如果你的时间字段不是int类型的话,可以直接使用:
// 全局配置方式 ,开启自动写入时间戳字段 'auto_timestamp' => 'datetime', //单独开启 <?php namespace app\index\model; use think\Model; class User extends Model { protected $autoWriteTimestamp = 'datetime'; }3、如果只需要在某些模型中开启时,可以先开启全局配置,然后在对应的模型中进行配置,如下
<?php namespace app\index\model; use think\Model; class User extends Model { protected $autoWriteTimestamp = false; }4、只需要一个字段时,比如需要使用create_time字段而不需要自动写入update_time,则可以单独关闭某个字段,例如:
class User extends Model { // 关闭自动写入update_time字段 protected $updateTime = false; }