自动写入创建和更新的时间戳字段(默认关闭)
两种方式配置
全局开启
数据库配置文件中设置
// 开启自动写入时间戳字段 'auto_timestamp' => true,
需要的模型类里面单独开启
use thinkModel;
class User extends Model{
protected $autoWriteTimestamp = true;
}或首先在数据库配置文件中全局开启
在不需要使用自动时间戳写入的模型类中单独关闭
use thinkModel;
class User extends Model{
protected $autoWriteTimestamp = false;
}配置开启自动写入create_time和update_time两个字段的值 默认为整型(int)
如果你的时间字段不是int类型
// 开启自动写入时间戳字段 'auto_timestamp' => 'datetime',
或
use thinkModel;
class User extends Model{
protected $autoWriteTimestamp = 'datetime';
}默认的创建时间字段为create_time 更新时间字段为update_time
支持的字段类型包括timestamp/datetime/int
写入数据时 系统写入create_time和update_time字段
不需要定义修改器
$user = new User(); $user->name = 'think'; $user->save(); echo $user->create_time; // 输出类似 2016-10-12 14:20:10 echo $user->update_time; // 输出类似 2016-10-12 14:20:10
时间字段的自动写入仅针对模型的写入方法 数据库的更新或写入方法无效
时间字段输出的时候会自动进行格式转换
不希望自动格式化输出 可以把数据库配置文件的datetime_format参数值改为false
datetime_format参数支持设置为时间类名
便于更多的时间处理
// 设置时间字段的格式化类 'datetime_format' => 'orgutilDateTime',
该类应该包含个__toString方法定义以确保能正常写入数据库
如果数据表字段不是默认值
use thinkModel;
class User extends Model {// 定义时间戳字段名
protected $createTime = 'create_at';
protected $updateTime = 'update_at';
}$user = new User(); $user->name = 'thinkphp'; $user->save(); echo $user->create_at; // 输出类似 2016-10-12 14:20:10 echo $user->update_at; // 输出类似 2016-10-12 14:20:10
如果只需要使用create_time字段而不需要自动写入update_time 单独关闭某个字段
class User extends Model {// 关闭自动写入update_time字段
protected $updateTime = false;
}动态关闭时间戳写入功能
例如更新阅读数的时候不修改更新时间 可以使用isAutoWriteTimestamp方法:
$user = User::get(1); $user->read +=1; $user->isAutoWriteTimestamp(false)->save();

尊贵的董事大人
英文标题不为空时 视为本栏投稿
需要关键字 描述 英文标题