doudu5498 2013-04-05 11:55
浏览 168
已采纳

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

Typically, the Laravel platform have a $table->timestamps(); in migration..., it generate two datetime fields, 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.

  • 写回答

5条回答 默认 最新

  • doujiao6116 2013-04-12 14:29
    关注

    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 DateTime class. But I digress, to use unix timestamps...

    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 = true in your models.

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

    // 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 {
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?