如何使我自己的时间戳方法在Laravel


How to make my own timestamp method in Laravel?

通常,Laravel平台有一个$table->timestamps();在迁移…生成两个datetime场,但我想实现我自己的时间戳,或者,也许叫unix_timestamps()。我想有两个名为created_atupdated_at的字段,它们存储unix时间戳,我如何实现它?谢谢。

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

  1. 在Schema(迁移)中,使用

    $table->integer('created_at');
    $table->integer('updated_at');
    
    不是

    $table->timestamps();
    
  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 {
}

For Laravel 4:

  • 重写Eloquent模型中的freshTimestamp()方法
  • 在迁移文件中使用整数代替时间戳

模型/product.php

class Product extends Eloquent {
    protected $table = 'products';
    public function freshTimestamp()
    {
        return time();
    }
}

Laravel 4还将所有日期/时间戳更改为Carbon实例(此处有文档记录)

这意味着您还需要覆盖getDates()方法,以防止Carbon在插入之前破坏您的时间戳。

public function getDates()
{
    return array();
}

数据库迁移/2013 _04_20_125823_create_products_table.php :

public function up()
{
    Schema::create('products', function(Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('created_at');
        $table->integer('updated_at');
    });
}

我担心,为了重写timestamps()函数,您将需要一些丑陋的hack,我确信这不是一个好主意。

如果需要自己的格式,只需定义一个新列。在Laravel的模式构建器中甚至有一个时间戳列(查看可用格式的完整列表):

$table->timestamp('added_on');
但是,您需要自己定义默认值和/或ON UPDATE,或者您可以使用触发器。但最终你最好还是坚持使用Laravel的timestamps(),因为它会自动处理所有事情。你为什么还需要别的东西?

我也有同样的需求,并想出了一个可能也适用于您的解决方案。我在Github上发布了我是如何做到的:Laravel Integer SQL Dates <==查看更多细节,但这里是它的要点:

class Base extends Eloquent {
  public function freshTimestamp()
  {
    return time(); // (int) instead of '2000-00-00 00:00:00'
  }
  public function fromDateTime($value)
  {
    return $value; // Don't mutate our (int) on INSERT!
  }
  // Uncomment, if you don't want Carbon API on SELECTs
  // protected function asDateTime($value)
  // {
  //   return $value;
  // }
  public function getDateFormat()
  {
    return 'U'; // PHP date() Seconds since the Unix Epoch
  }
}
class User extends Base {
  protected $table = 'users';
  protected $fillable = ['email'];
}

创建一个时间戳类型的migrations/model字段,然后在控制器中使用

填充当前时间
$myField = new 'DateTime();