方法一:
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 Illuminate/Database/Eloquent/Model::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的幾種方法總結就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選