Laravel ORM 只開啓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”: “2020-09-27 13:47:12.000000”,
“timezone_type”: 3,
“timezone”: “Asia/Shanghai”
},
並不是想象中的
“created_at”: “2020-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.
  //}
}

在Migration中也可以設置(具體沒試過,在別的文章裏看見的)

class CreatePostsTable extends Migration {
  public function up() {
   Schema::create('posts', function(Blueprint $table) {
   $table->timestamp('created_at')
   ->default(DB::raw('CURRENT_TIMESTAMP'));
  });
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章