laravel 5 ,如何自动处理 created_at 而不是 updated_at

laravel 5 , how to handle created_at automatically but not the updated_at

如laravel的文档所述,eloquent可以处理created_at和updated_at字段,如果我只想laravel怎么办照顾 created_at,并留下 updated_at?

实现上述目标的一种方法是改变模型事件。将以下方法添加到您的模型中。

public static function boot()
{
    public $timestamps = false;
    parent::boot();

    static::creating(function($model) {
        $dateTime = new DateTime;
        $model->created_at = $dateTime->format('m-d-y H:i:s');
        return true;
    });

    static::updating(function($model) {
        $dateTime = new DateTime;
        $model->updated_at = $dateTime->format('m-d-y H:i:s');
        return true;
    });
}

现在您可以访问创建和更新模型事件。在这些事件中,你可以做任何你想做的事,在你的情况下你可以改变时间戳。有关模型事件的更多信息,请参阅 Laravel 文档 Model Events

Eloquent 处理 updateTimestamps():

中的时间戳
protected function updateTimestamps()
{
    $time = $this->freshTimestamp();

    if ( ! $this->isDirty(static::UPDATED_AT))
    {
        $this->setUpdatedAt($time);
    }

    if ( ! $this->exists && ! $this->isDirty(static::CREATED_AT))
    {
        $this->setCreatedAt($time);
    }
}

您只需在您的模型中覆盖此函数并删除 updatedAt 部分:

protected function updateTimestamps()
{
    $time = $this->freshTimestamp();

    if ( ! $this->exists && ! $this->isDirty(static::CREATED_AT))
    {
        $this->setCreatedAt($time);
    }
}

或者您可以只覆盖 setUpdatedAt,尽管您可能希望保留它以有意设置值:

public function setUpdatedAt($value)
{
    // do nothing
}

开箱即用的功能全有或全无。

仅复制 created_at 的功能,您可以使用 eloquent 事件。对于您的每个模型,您可以执行以下操作

class MyModel extends Eloquent
{

    protected $timestamps = false;

    public static function boot()
    {
        parent::boot();

        static::creating(function($model)
        {
            $model->created_at = Carbon::now();
        });
    }

}

每次创建新模型时,都会使用 Carbon 将 created_at 列设置为当前时间。