Laravel Eloquent:修改 created_at 和 updated_at 名称 1 个改进

有时候我们在一个已有的数据库上使用 Laravel 进行开发,通常表的创建和更新时间的字段名并不是created_atupdated_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();
        });
    }

}
本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 2

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!