Laravel Eloquent:修改 created_at 和 updated_at 名称
有时候我们在一个已有的数据库上使用 Laravel 进行开发,通常表的创建和更新时间的字段名并不是created_at和updated_at,也有时候只有一个创建时间而没有更新时间,那么我们在数据模型定义的时候该怎么处理呢?
这里提供两种方法。
第一种、重写常量(推荐)
class User extends Eloquent {
const CREATED_AT = 'post_date';
const UPDATED_AT = 'post_modified';
}
这样子 getCreatedAtColumn 和 getUpdatedAtColumn 就会对应的返回 post_date 和 post_modified 字段了。而更新的时候,也会使用新的字段名称。
第二种、模型事件
class User extends Eloquent {
public $timestamps = false;
public static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->created = $model->freshTimestampString();
});
static::updating(function ($model) {
$model->updated = $model->freshTimestampString();
});
}
}
Laravel 社区 Wiki
关于 LearnKu
推荐文章: