如何在Laravel中创建自己的时间戳方法?

DNB*_*ims 4 php laravel laravel-3

通常情况下,Laravel平台有一个$table->timestamps(); 迁移...,它会生成两个datetime字段,但我想实现自己的时间戳,或者可能是调用unix_timestamps().我想有两个名为created_at,并且updated_at存储unix时间戳的字段,我该如何实现呢?谢谢.

Phi*_*rks 7

您不必使用Laravel的时间戳助手,但它们很方便.现在也有一些处理字符串时间戳的好方法,包括PHP的DateTime类.但我离题了,使用unix时间戳......

  1. 在您的架构(迁移)中,使用

    $table->integer('created_at');
    $table->integer('updated_at');
    
    Run Code Online (Sandbox Code Playgroud)

    代替

    $table->timestamps();
    
    Run Code Online (Sandbox Code Playgroud)
  2. 更换timestamp()模型中的功能.

  3. 保留$timestamps = true在您的模型中.

以下是您可以使用的示例基本模型,并在您的模型上扩展而不是Eloquent:

// models/basemodel.php
class BaseModel extends Eloquent {

    /**
     * Indicates if the model has update and creation timestamps.
     *
     * @var bool
     */
    public static $timestamps = true;

    /**
     * Set the update and creation timestamps on the model.
     */
    public function timestamp()
    {
        $this->updated_at = time();

        if ( ! $this->exists) $this->created_at = $this->updated_at;
    }
}

// models/thing.php
class Thing extends BaseModel {

}
Run Code Online (Sandbox Code Playgroud)