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 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳