当前位置:首页 > PHP教程 > PHP常见问题

laravelORM只开启created_at的几种方法总结

方法一:

class user extends model {
  public $timestamps = false;//关闭自动维护
  public static function boot() {
    parent::boot();
    #只添加created_at不添加updated_at
    static::creating(function ($model) {
      $model->created_at = $model->freshtimestamp();
      //$model->updated_at = $model->freshtimestamp();
    });
  }
}
此处有坑:使用create方法创建一条记录时返回值的created的值是这样的: 
“created_at”: { 
“date”: “2017-09-27 13:47:12.000000”, 
“timezone_type”: 3, 
“timezone”: “asia/shanghai” 
}, 
并不是想象中的 
“created_at”: “2017-09-27 13:49:39”, 

方法二:

class user extends model {
  const updated_at = null;//设置update_at为null
  //const created_at = null;
}
此处有坑:使用destroy删除会报错 
missing argument 2 for illuminatedatabaseeloquentmodel::setattribute() 
使用delete不影响,wherein也不影响

方法三:

class user extends model {
  //重写setupdatedat方法
  public function setupdatedat($value) {
    // do nothing.
  }
  //public function setcreatedat($value)
  //{
    // do nothing.
  //}
}

方法四:

class user extends model {
  //重写setupdatedat方法
  public function setupdatedatattribute($value) {
    // do nothing.
  }
  //public function setcreatedatattribute($value)
  //{
    // do nothing.
  //}
}

ps:

在migration中也可以设置(具体没试过,在别的文章里看见的)

class createpoststable extends migration {
  public function up() {
   schema::create('posts', function(blueprint $table) {
   $table->timestamp('created_at')
   ->default(db::raw('current_timestamp'));
  });
}

以上这篇laravel orm 只开启created_at的几种方法总结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持硕编程。


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!