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条)

报告相同问题?

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名