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

时间:2013-04-05 11:55:38

标签: php laravel laravel-3

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

5 个答案:

答案 0 :(得分:7)

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

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

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

    而不是

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

  3. 在模特中保留$timestamps = true
  4. 以下是您可以使用的示例基本模型,并在您的模型上扩展而不是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 {
    
    }
    

答案 1 :(得分:4)

对于Laravel 4:

  • 覆盖您的Eloquent模型中的freshTimestamp()方法
  • 在迁移文件中使用整数而不是时间戳

<强>模型/ product.php

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

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

Laravel 4还将所有日期/时间戳变为Carbon实例(已记录here

这意味着您还需要覆盖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');
    });
}

答案 2 :(得分:3)

我担心你需要一些丑陋的黑客来重写timestamps()功能,我确信这是个坏主意。

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

$table->timestamp('added_on');

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

答案 3 :(得分:2)

我有同样的要求,并找出了一个可能对你有用的解决方案。我在Github上发布了一个关于我是如何做到的回购:Laravel Integer SQL Dates&lt; ==查看更多细节,但这是它的要点:

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'];
}

答案 4 :(得分:1)

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

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