如何在 Laravel 中制作我自己的时间戳方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15833335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:40:31  来源:igfitidea点击:

How to make my own timestamp method in Laravel?

phplaravellaravel-3

提问by DNB5brims

Typically, the Laravel platform have a $table->timestamps();in migration..., it generate two datetimefields, But I would like to implement my own timestamps or, maybe call unix_timestamps(). I would like to have two fields named created_at, and updated_at, and which store the unix timestamps, how can I implement it? Thanks.

通常,Laravel 平台有一个$table->timestamps();in migration...,它生成两个datetime字段,但我想实现我自己的时间戳,或者调用unix_timestamps(). 我想有两个名为created_at, 和 的字段,updated_at它们存储unix时间戳,我该如何实现?谢谢。

回答by Phill Sparks

You don't have to use Laravel's timestamp helpers, but they are convenient. There are some good ways of working with string timestamps now too, including PHP's DateTimeclass. But I digress, to use unix timestamps...

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

  1. In your Schema (migration), use

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

    instead of

    $table->timestamps();
    
  2. Replace the timestamp()function in your models.

  3. Keep $timestamps = truein your models.
  1. 在您的架构(迁移)中,使用

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

    代替

    $table->timestamps();
    
  2. 替换timestamp()模型中的函数。

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

Here's an example base model which you could use, and extend instead of Eloquent on your models:

这是您可以使用的示例基础模型,并在您的模型上扩展而不是 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 {

}

回答by Dirk

For Laravel 4:

对于 Laravel 4:

  • override the freshTimestamp() method in your Eloquent model
  • use integers in migration file in stead of timestamps
  • 覆盖 Eloquent 模型中的 freshTimestamp() 方法
  • 在迁移文件中使用整数而不是时间戳

models/product.php

模型/product.php

class Product extends Eloquent {
    protected $table = 'products';

    public function freshTimestamp()
    {
        return time();
    }
}

Laravel 4 also mutates all dates/timestamps to Carbon instances (Documented here)

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

Which means you also need to overwrite the getDates()method in order to prevent Carbon ruining your timestamp before insertion.

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

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

database/migrations/2013_04_20_125823_create_products_table.php:

数据库/迁移/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');
    });
}

回答by Adrenaxus

I fear that you'll need some ugly hacks in order to rewrite the timestamps()function, and I'm sure that's a bad idea.

我担心你需要一些丑陋的技巧来重写这个timestamps()函数,我相信这是一个坏主意。

If you need your own format, simply define a new column. There is even a timestamp column in Laravel's schema builder (see herefor a full list of available formats):

如果您需要自己的格式,只需定义一个新列。Laravel 的模式构建器中甚至还有一个时间戳列(有关可用格式的完整列表,请参见此处):

$table->timestamp('added_on');

You would however need to define default values and/or ON UPDATEby yourself, or you could use triggers. But in the end you're probably best off sticking to Laravel's timestamps(), because it will take care of everything automatically. Why would you need anything else?

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

回答by J W

I had this same requirement and figured out a solution that may work for you too. I posted a repo of how I did it on Github: Laravel Integer SQL Dates<== check it out for more details, but here's the gist of it:

我有同样的要求,并想出了一个可能对你有用的解决方案。我在 Github 上发布了一个关于我如何做的 repo: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'];
}

回答by Bonfix Ngetich

Just create a migrations/model field that is a timestamp type, then in your controller, fill it with current time using this

只需创建一个时间戳类型的迁移/模型字段,然后在您的控制器中,使用当前时间填充它

$myField = new \DateTime();